package com.xebest.web.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xebest.api.dto.*;
import com.xebest.api.dto.resdto.ForErpOrderResDTO;
import com.xebest.api.dto.resdto.OrderInfoResDTO;
import com.xebest.api.dto.resdto.XeSysMsgRecordResDTO;
import com.xebest.api.service.ForErpOrderIApiService;
import com.xebest.api.service.OrderInfoApiService;
import com.xebest.api.service.XeSysMsgApiService;
import com.xebest.api.util.MonitorUtil;
import com.xebest.api.util.OpertorLogUtil;
import com.xebest.common.base.dto.BaseResponseDTO;
import com.xebest.common.enums.cms.SysCmsPagePlatEnum;
import com.xebest.common.enums.erp.aftersales.VenOrderRefundReasonEnum;
import com.xebest.common.enums.erp.aftersales.VenOrderRefundSourceEnum;
import com.xebest.common.enums.erp.aftersales.VenOrderRefundStatusEnum;
import com.xebest.common.enums.erp.aftersales.VenOrderRefundTypeEnum;
import com.xebest.common.enums.erp.order.*;
import com.xebest.common.enums.erp.purch.VenPurchCheckEnum;
import com.xebest.common.enums.erp.purch.VenPurchStatusEnum;
import com.xebest.common.enums.erp.purch.VenPurchTypeEnum;
import com.xebest.common.enums.erp.storehouse.VenStoreInventoryFlagEnum;
import com.xebest.common.enums.erp.storehouse.VenStoreNegativeFlagEnum;
import com.xebest.common.enums.erp.storehouse.VenStoreTmsStatusEnum;
import com.xebest.common.enums.erp.storehouse.VenStoreTypeEnum;
import com.xebest.common.enums.erp.sys.VenDelEnum;
import com.xebest.common.enums.logtype.ErpLogTypeEnum;
import com.xebest.common.util.XeBaseUtil;
import com.xebest.config.CancelOrderSender;
import com.xebest.constant.XeConstans;
import com.xebest.constant.XeErrorCode;
import com.xebest.constant.XeSmsConstans;
import com.xebest.util.CalUtils;
import com.xebest.util.OrderBeanUtils;
import com.xebest.util.XeVenBusConstans;
import com.xebest.util.msg.XeVenOrderMsg;
import com.xebest.util.seq.FinanceSeqUtil;
import com.xebest.util.seq.PurchSeqUtil;
import com.xebest.util.seq.StoreHouseSeqUtil;
import com.xebest.web.form.*;
import com.xebest.web.mapper.read.XeVenOrderLogisticsReadMapper;
import com.xebest.web.mapper.read.XeVenOrderReadMapper;
import com.xebest.web.mapper.read.XeVenOrderRefundReadMapper;
import com.xebest.web.mapper.read.XeVenStoreInfoReadMapper;
import com.xebest.web.mapper.write.*;
import com.xebest.web.model.*;
import com.xebest.web.service.*;
import com.xebest.web.view.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toList;

/**
 * 订单相关操作
 *
 * @author ruancz
 */
@Service
public class XeVenOrderServiceImpl implements XeVenOrderService {

    private static final Logger log = LoggerFactory.getLogger(XeVenOrderServiceImpl.class);//日志记录类

    @Autowired
    private XeVenOrderReadMapper xeVenOrderReadMapper;  //查询订单业务操作
    @Autowired
    private XeVenOrderLogisticsReadMapper xeVenOrderLogisticsReadMapper;
    @Autowired
    private XeVenOrderWriteMapper xeVenOrderWriteMapper; //更新订单业务操作

    @Autowired
    private XeVenStoreInventoryService xeVenStoreInventoryService;//库存一览操作

    @Autowired
    private XeVenStoreInfoReadMapper xeVenStoreInfoReadMapper;//查询仓库操作

    @Autowired
    private XeVenPurchOrderWriteMapper xeVenPurchOrderWriteMapper;//新增采购单操作

    @Autowired
    private XeVenPurchOrderDetailWriteMapper xeVenPurchOrderDetailWriteMapper;//新增采购单操作

    @Autowired
    private XeVenOrderRefundWriteMapper xeVenOrderRefundWriteMapper;//操作退款信息

    @Autowired
    private XeVenOrderRefundReadMapper xeVenOrderRefundReadMapper;

    @Autowired
    private XeVenOrderRefundDetailWriteMapper xeVenOrderRefundDetailWriteMapper;//操作退款明细信息

    @Autowired
    private SupplyChainService supplyChainService;//供应链操作类

    @Autowired
    private XeVenEpayService xeVenEpayService;//易支付业务操作

    @Autowired
    private XeVenPurchService xeVenPurchService;//采购单

    @Autowired
    private XeSysMsgApiService xeSysMsgApiService;

    @Autowired
    private XeBaseUtil xeBaseUtil;

    @Autowired
    private XeVenOrderLogisticsService xeVenOrderLogisticsService;

    @Autowired
    private XeVenSummaryPurchService xeVenSummaryPurchService;

    @Autowired
    private ForErpOrderIApiService forErpOrderIApiService;

    @Autowired
    private OrderInfoApiService orderInfoApiService;


    /**
     * 查询订单列表接口
     *
     * @author ruancz
     * @since 2017年6月19日 下午4:46:31
     */
    @Override
    public List<XeVenOrderView> queryOrderInfoList(XeVenOrderForm orderForm, ErpUserInfo userInfo) {
        orderForm.setUserCode(userInfo.getUserCode());
        if (null == orderForm.getOrderByCreateTime() && null == orderForm.getOrderBySendTime()) {
            orderForm.setOrderByCreateTime(XeConstans._XE_TWO);
        }
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("orderForm", orderForm);
        if (XeConstans._XE_TWO == userInfo.getAdminFlag()) {
            if (StringUtils.isNotBlank(userInfo.getRoleIds())) {
                paramMap.put("roleId", userInfo.getRoleIds().split(","));
            } else {
                paramMap.put("roleId", null);
            }
            paramMap.put("admin", "noAdmin");
        } else {
            paramMap.put("admin", null);
        }
        List<XeVenOrderView> xeVenOrderViews = xeVenOrderReadMapper.queryOrderList(paramMap);
        if (null == xeVenOrderViews || xeVenOrderViews.size() == XeConstans._XE_ZERO) {
            return xeVenOrderViews;
        }
        for (int i = 0; i < xeVenOrderViews.size(); i++) {
            XeVenOrderView orderView = xeVenOrderViews.get(i);
            if (orderView.getPromotOrderType() != null && orderView.getPromotOrderType().equals(4)) {
                orderView.setOrderMark(orderView.getOrderMark() + ",8");
            }
            if (StringUtils.isNotBlank(orderView.getCaAreaId())) {
                String orgAreaName = xeBaseUtil.getOrgAreaName(Integer.parseInt(orderView.getCaAreaId().trim()));
                orderView.setCaArea(orgAreaName);
            } else if (StringUtils.isNotBlank(orderView.getCaCityId())) {
                String caCityName = xeBaseUtil.getAreaName(Integer.parseInt(orderView.getCaCityId().trim()));
                String caProvinceName = xeBaseUtil.getAreaName(Integer.parseInt(orderView.getCaProvinceId().trim()));
                orderView.setCaArea(caProvinceName + "-" + caCityName);
            }
            /**
             * 1、  在线支付订单：
             *	 ①订单同步过来后：应收金额=订单金额
             *	 ②待付款且修改运费/特批优惠：订单金额变化，应收金额也跟随变化
             *	 ③待付款：实收金额=0、已支付：实收金额=订单金额=支付金额（支付后实收金额不会再变）
             *	 ④确认实发量后：应收金额=订单实发金额+实发运费金额；实收金额不变
             *
             *	 2、货到付款订单：
             *	 ①订单同步过来后：实收金额=0、应收金额=订单金额
             *	 ②修改运费/特批优惠：订单金额变化，应收金额也跟随变化；实收金额=0
             *	 ③确认实发量后：应收金额=订单实发金额+实发运费金额；
             *	 ④订单完成后：实收金额=应收金额
             *
             */
            //应收金额
            orderView.setReceiptsAmount(orderView.getPayAbleAmount());
            //确认实发之后 应收金额
            if (orderView.getConfirmSendNum().equals(VenConfirmSendNumEnum.YES.getValue())) {
                orderView.setReceiptsAmount(orderView.getEpayReceAmt());
            }
            //实收金额
            orderView.setReceivableAmount(new BigDecimal("0"));
            //货到付款 订单已完成
            if (orderView.getPayType().equals(VenOrderPayTypeEnum.ARRIVE_PAY.getValue().toString()) && orderView.getOrderStatus().equals(VenOrderStatusEnum.FINISH.getValue().toString())) {
                orderView.setReceivableAmount(orderView.getEpayReceAmt());
            }
            //在线支付已支付
            if (orderView.getPayType().equals(VenOrderPayTypeEnum.ONLINE_PAY.getValue().toString()) && orderView.getPayStatus().equals(VenOrderPayStatusEnum.ALL_PAID.getValue().toString())) { //在线支付
                orderView.setReceivableAmount(orderView.getPayAbleAmount());
            }
            orderForm.setOrderId(orderView.getOrderId());
            Map<String, Object> resultMap = xeVenOrderReadMapper.queryRefundAmount(orderForm);
            if (null != resultMap) {
                //退款金额
                if (resultMap.containsKey("refundAmount") && StringUtils.isNotBlank(resultMap.get("refundAmount").toString())) {
                    orderView.setRefundAmount(new BigDecimal(resultMap.get("refundAmount").toString()));
                }
                if (orderView.getConfirmSendNum().equals(VenConfirmSendNumEnum.YES.getValue())) {
                    //确认实发之后 应收金额
                    orderView.setReceiptsAmount(orderView.getEpayReceAmt());
                    //有实发差异
                    if (resultMap.containsKey("sfRefundAmount") && StringUtils.isNotBlank(resultMap.get("sfRefundAmount").toString())) {
                        //差异金额
                        orderView.setSfRefundAmount(new BigDecimal(resultMap.get("sfRefundAmount").toString()));
                        //差异运费金额
                        orderView.setFreRefundAmount(orderView.getDifferenceAmount().subtract(orderView.getSfRefundAmount()));
                        //实发金额
                        //orderView.setActualAmout(orderView.getEpayReceAmt().subtract(orderView.getFreRefundAmount()));
                        //实发运费
                        // orderView.setActualFreAmout(orderView.getFreAmount().subtract(orderView.getActualFreAmout()));
                        //实发运费 = 运费总额-差异运费   20180704 李贝贝 add v3.1.4
                        orderView.setActualFreAmout(orderView.getFreAmount().subtract(orderView.getFreRefundAmount()));
                        //实发金额 = 应收金额-实发运费
                        orderView.setActualAmout(orderView.getEpayReceAmt().subtract(orderView.getActualFreAmout()));

                    } else {
                        //差异金额
                        orderView.setSfRefundAmount(new BigDecimal("0"));
                        //差异运费金额
                        orderView.setFreRefundAmount(new BigDecimal("0"));
                        //实发金额
                        orderView.setActualAmout(orderView.getEpayReceAmt());
                        //实发运费
                        orderView.setActualFreAmout(orderView.getFreAmount());
                    }
                }
            }
        }
        return xeVenOrderViews;
    }

    /**
     * 统计订单数据
     */
    @Override
    public List<Map<String, Object>> queryCountOrderInfo(XeVenOrderForm form, ErpUserInfo userInfo) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        form.setUserCode(userInfo.getUserCode());
        paramMap.put("orderForm", form);
        if (XeConstans._XE_TWO == userInfo.getAdminFlag()) {
            if (StringUtils.isNotBlank(userInfo.getRoleIds())) {
                paramMap.put("roleId", userInfo.getRoleIds().split(","));
            } else {
                paramMap.put("roleId", null);
            }
            paramMap.put("admin", "noAdmin");
        } else {
            paramMap.put("admin", null);
        }
        List<Map<String, Object>> list = this.xeVenOrderReadMapper.queryCountOrderInfo(paramMap);
        return list;
    }

    /**
     * 根据日 月 年等统计订单数
     *
     * @param map paramType =1 日
     *            paramType=2 月
     *            paramType=3 年
     *            paramValue 参数值
     * @author chenjing
     * @since 15:41 2017/11/24
     */
    @Override
    public BigDecimal queryOrderCountByParams(Map<String, Object> map) {
        if (null == map || !map.containsKey("paramType") || !map.containsKey("paramValue")
                || null == map.get("paramType") || null == map.get("paramValue")) {
            return new BigDecimal(0);
        }
        return xeVenOrderReadMapper.queryOrderCountByParams(map);
    }

    /**
     * 根据日 月 年等统计订单数
     *
     * @param map paramType =1 日
     *            paramType=2 月
     *            paramType=3 年
     *            paramValue 参数值
     * @author chenjing
     * @since 15:41 2017/11/24
     */
    @Override
    public BigDecimal queryMonthTotalAmountByParams(Map<String, Object> map) {
        if (null == map || !map.containsKey("paramType") || !map.containsKey("paramValue")
                || null == map.get("paramType") || null == map.get("paramValue")) {
            return new BigDecimal(0);
        }
        return xeVenOrderReadMapper.queryMonthTotalAmountByParams(map);
    }

    /**
     * 根据日 月 年等统计交易客户数
     *
     * @param map paramType =1 日
     *            paramType=2 月
     *            paramType=3 年
     *            paramValue 参数值
     * @author chenjing
     * @since 15:41 2017/11/24
     */
    @Override
    public BigDecimal queryMonthTradeUserNumByParams(Map<String, Object> map) {
        if (null == map || !map.containsKey("paramType") || !map.containsKey("paramValue")
                || null == map.get("paramType") || null == map.get("paramValue")) {
            return new BigDecimal(0);
        }
        return xeVenOrderReadMapper.queryMonthTradeUserNumByParams(map);
    }

    /**
     * 根据日 月 年等统计交易客户数
     *
     * @param map paramType =1 日
     *            paramType=2 月
     *            paramType=3 年
     *            paramValue 参数值
     * @author chenjing
     * @since 15:41 2017/11/24
     */
    @Override
    public List<Map<String, Object>> queryProOrgCountByParams(Map<String, Object> map) {
        if (null == map || !map.containsKey("paramType") || !map.containsKey("paramValue")
                || null == map.get("paramType") || null == map.get("paramValue")) {
            return new ArrayList<>();
        }
        return xeVenOrderReadMapper.queryProOrgCountByParams(map);
    }

    /**
     * 统计每月的日销售额和订单数
     *
     * @author chenjing
     * @since 11:27 2017/11/27
     */
    @Override
    public List<Map<String, Object>> queryOrderCountAmountByParams(Map<String, Object> map) {
        return xeVenOrderReadMapper.queryOrderCountAmountByParams(map);
    }


    /**
     * 查询订单明细
     *
     * @author ruancz
     * @since 2017年6月19日 下午4:46:31
     */
    @Override
    public Map<String, Object> queryOrderInfoDetail(String orderId, ErpUserInfo userInfo) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("orderId", orderId);
        map.put("userCode", userInfo.getUserCode());
        List<XeVenOrderDetailView> orderInfoDetailList = xeVenOrderReadMapper.queryOrderInfoDetailByParam(map);
        for (XeVenOrderDetailView detailView : orderInfoDetailList) {
            BigDecimal sendAmt = XeBaseUtil.baseUtil.calSendAmt(detailView.getPurchaseNum(), detailView.getRealSendNum(), detailView.getProTotalPrice(), detailView.getPmtAmount());
            detailView.setSendAmount(sendAmt);//设置发货金额
        }
        map.remove("orderId");
        map.remove("userCode");
        map.put("orderInfoDetail", orderInfoDetailList);
        return map;
    }

    /**
     * 修改订单
     *
     * @author ruancz
     * @since 2017年6月19日 下午4:46:31
     */
    @Override
    @Transactional(value = "writeTransactionManager")
    public int updateOrderInfo(XeVenOrderForm xeVenOrderForms, ErpUserInfo userInfo) throws Exception {
        XeVenOrderInfoEntity orderInfoEntity = OrderBeanUtils.toXeVenOrderInfoEntity(xeVenOrderForms);
        orderInfoEntity.setModfiyUser(userInfo.getLoginName());
        return this.xeVenOrderWriteMapper.updateXeVenOrderInfo(orderInfoEntity);
    }

    /**
     * 站库存
     *
     * @author ruancz
     * @since 2017年6月29日 下午2:20:05
     */
    @Override
    public int judeExceptionOrder(XeVenOrderInfoEntity venOrderInfoEntity, XeVenStoreInfoEntity storeInfo,
                                  List<XeVenOrderInfoDetailEntity> orderInfoDetailList) throws Exception {

        log.info("订单号: {},开始占库存...", venOrderInfoEntity.getOrderId());
        //树立标识位  判断库存是否足够 以及负库存
        int result = 0;
        //是否记录库存
        if (storeInfo.getRecordInventoryFlag() == VenStoreInventoryFlagEnum.YES.getValue()) {
            XeVenStoreInventoryEntity inventory = new XeVenStoreInventoryEntity();
            inventory.setUserCode(venOrderInfoEntity.getUserCode());
            inventory.setStoreId(storeInfo.getStoreId());
            inventory.setModifyUser(venOrderInfoEntity.getModfiyUser());
            //允许负库存
            if (storeInfo.getNegativeFlag() == VenStoreNegativeFlagEnum.YES.getValue()) {
                for (int j = 0; j < orderInfoDetailList.size(); j++) {
                    XeVenOrderInfoDetailEntity xeVenOrderInfoDetailEntity = orderInfoDetailList.get(j);
                    inventory.setProSku(xeVenOrderInfoDetailEntity.getProSku());
                    inventory.setLockedInv(xeVenOrderInfoDetailEntity.getPurchaseNum());
                    inventory.setUserCode(venOrderInfoEntity.getUserCode());
                    //更新库存
                    int flag = this.xeVenStoreInventoryService.updateStoreInvByStoreInventoryEntity(inventory, null);
                    if (flag > XeConstans._XE_ZERO) {
                        inventory.setUserCode(venOrderInfoEntity.getUserCode());
                        xeVenOrderInfoDetailEntity.setInventoryFlag(VenStoreNegativeFlagEnum.YES.getValue());
                        xeVenOrderInfoDetailEntity.setModifyUser(venOrderInfoEntity.getModfiyUser());
                        this.xeVenOrderWriteMapper.updateXeVenOrderInfoDetail(xeVenOrderInfoDetailEntity);
                        result += flag;
                    } else {
                        //更新不成功 置为库存不足
                        log.info("订单明细: {},库存不足或没有商品,置为库存不足...", xeVenOrderInfoDetailEntity.getItemId());
                        inventory.setUserCode(venOrderInfoEntity.getUserCode());
                        xeVenOrderInfoDetailEntity.setInventoryFlag(VenStoreNegativeFlagEnum.NO.getValue());
                        xeVenOrderInfoDetailEntity.setModifyUser(venOrderInfoEntity.getModfiyUser());
                        this.xeVenOrderWriteMapper.updateXeVenOrderInfoDetail(xeVenOrderInfoDetailEntity);
                    }
                }
            } else {
                //不允许负库存
                for (int j = 0; j < orderInfoDetailList.size(); j++) {
                    XeVenOrderInfoDetailEntity xeVenOrderInfoDetailEntity = orderInfoDetailList.get(j);
                    inventory.setProSku(xeVenOrderInfoDetailEntity.getProSku());
                    inventory.setLockedInv(xeVenOrderInfoDetailEntity.getPurchaseNum());
                    inventory.setUserCode(venOrderInfoEntity.getUserCode());
                    int flag = this.xeVenStoreInventoryService.updateStoreInvByStoreInventoryEntity(inventory, xeVenOrderInfoDetailEntity.getPurchaseNum());
                    if (flag > XeConstans._XE_ZERO) {
                        inventory.setUserCode(venOrderInfoEntity.getUserCode());
                        xeVenOrderInfoDetailEntity.setInventoryFlag(VenStoreNegativeFlagEnum.YES.getValue());
                        xeVenOrderInfoDetailEntity.setModifyUser(venOrderInfoEntity.getModfiyUser());
                        this.xeVenOrderWriteMapper.updateXeVenOrderInfoDetail(xeVenOrderInfoDetailEntity);
                        result += flag;
                    } else {
                        log.info("订单明细: {},库存不足或没有商品,置为库存不足...", xeVenOrderInfoDetailEntity.getItemId());
                        xeVenOrderInfoDetailEntity.setInventoryFlag(VenStoreNegativeFlagEnum.NO.getValue());
                        xeVenOrderInfoDetailEntity.setModifyUser(venOrderInfoEntity.getModfiyUser());
                        inventory.setUserCode(venOrderInfoEntity.getUserCode());
                        orderInfoDetailList.get(j).setInventoryFlag(VenStoreNegativeFlagEnum.NO.getValue());
                        this.xeVenOrderWriteMapper.updateXeVenOrderInfoDetail(xeVenOrderInfoDetailEntity);
                    }
                }
            }

        } else {
            result = orderInfoDetailList.size();
        }
        log.info("订单号: {},占库存结束...", venOrderInfoEntity.getOrderId());
        return result;
    }

    /**
     * 取消订单/废单
     *
     * @author ruancz
     * @since 2017年6月19日 下午6:54:41
     */
    @Override
    @Transactional(value = "writeTransactionManager")
    public void cancelOrder(List<XeVenOrderForm> formList, ErpUserInfo userInfo, String requestIP) throws Exception {
        for (int i = 0; i < formList.size(); i++) {
            XeVenOrderForm orderForm = formList.get(i);
            if (orderForm.getOrderStatus() != VenOrderStatusEnum.WAIT_CHECK.getValue() || !VenOrderStatusEnum.WAIT_DIS.getValue().equals(orderForm.getOrderStatus())) {
                log.info("订单号: {},开始废弃订单...", orderForm.getOrderId());
                XeVenOrderInfoEntity orderInfo = JSON.parseObject(JSON.toJSONString(orderForm), XeVenOrderInfoEntity.class);
                orderInfo.setCancelTime(new Date());
                orderInfo.setCancelUser(userInfo.getLoginName());
                orderInfo.setModfiyUser(userInfo.getLoginName());
                orderInfo.setOrderException(VenOrderExpFlagEnum.NO_PROBLEM.getValue());
                orderInfo.setUserCode(userInfo.getUserCode());
                orderInfo.setOrderStatus(VenOrderStatusEnum.CANCEL.getValue());
                int flag = this.xeVenOrderWriteMapper.updateXeVenOrderInfo(orderInfo);
                if (XeConstans._XE_ONE == flag) {
                    judeCancelOrder(orderInfo, userInfo);
                    insertMqLog(ErpLogTypeEnum.erpOrderModifyCancel.getValue(), orderInfo.getOrderId(), "作废订单【" + orderInfo.getOrderId() + "】，作废原因：" + orderInfo.getCancelRemark() + "。", userInfo, requestIP, null);
                }
            }
        }
    }

    /**
     * 修改特批优惠金额
     *
     * @author ruancz
     * @since 2017年6月20日 下午6:54:41
     */
    @Override
    @Transactional(value = "writeTransactionManager")
    public int updateSpecialDisamount(List<XeVenOrderForm> xeVenOrderForm, ErpUserInfo userInfo, String requestIP) throws Exception {
//		List<XeVenOrderInfoDetailEntity> orderinfoEntityList = JSON.parseArray(JSON.toJSONString(xeVenOrderForm),XeVenOrderInfoDetailEntity.class);
        XeVenOrderForm orderForm = xeVenOrderForm.get(XeConstans._XE_ZERO);

        // 调用前台接口同步特批优惠金额
        ForErpOrderDTO erpOrderDTO = new ForErpOrderDTO();
        erpOrderDTO.setOrderId(orderForm.getOrderId());
        erpOrderDTO.setModfiyUser(userInfo.getLoginName());
        erpOrderDTO.setUserId(orderForm.getUserId());
        List<String> itemId = new ArrayList<String>();
        List<String> specialAmount = new ArrayList<String>();
        List<String> specialPrice = new ArrayList<String>();
        List<String> oldSpecialAmount = new ArrayList<String>();
        String orderMark = "";
        StringBuffer operContent = new StringBuffer();
        for (int i = 0; i < xeVenOrderForm.size(); i++) {
            XeVenOrderForm venOrderForm = xeVenOrderForm.get(i);
            orderMark = venOrderForm.getOrderMark();
            BigDecimal oldSpecDisamount = venOrderForm.getOldSpecDisamount() == null ? new BigDecimal("0") : venOrderForm.getOldSpecDisamount();
            BigDecimal specDisamount = venOrderForm.getSpecDisamount() == null ? new BigDecimal("0") : venOrderForm.getSpecDisamount();
            BigDecimal specPrice = venOrderForm.getSpecPrice() == null ? new BigDecimal("0") : venOrderForm.getSpecPrice();
            if (oldSpecDisamount.compareTo(specDisamount) != XeConstans._XE_ZERO) {
                operContent.append("修改订单【" + erpOrderDTO.getOrderId() + "】内【" + venOrderForm.getProSku() + "】的特批优惠金额为【¥" + specDisamount.toString() + "】，旧金额为：" + oldSpecDisamount.toString());
                itemId.add(venOrderForm.getItemId());
                specialAmount.add(specDisamount.toString());
                oldSpecialAmount.add(oldSpecDisamount.toString());
                specialPrice.add(specPrice.toString());//传递特批单价
            }
            if (itemId != null && itemId.size() > 0) {
                erpOrderDTO.setPecialPrices((String[]) specialPrice.toArray(new String[itemId.size()]));
                erpOrderDTO.setItemIds((String[]) itemId.toArray(new String[itemId.size()]));
                erpOrderDTO.setSpecialAmounts((String[]) specialAmount.toArray(new String[itemId.size()]));
                erpOrderDTO.setOldSpecialAmounts((String[]) oldSpecialAmount.toArray(new String[itemId.size()]));
            }
        }
        int result = 0;
        if (itemId != null && itemId.size() > 0) {
            log.info("修改特批优惠金额同步入参 :{}", JSON.toJSONString(erpOrderDTO));
            ForErpOrderResDTO forErpOrderResDTO = this.forErpOrderIApiService.modifyOrderPrice(erpOrderDTO);
            log.info("修改特批优惠金额同步出参 :{}", JSON.toJSONString(forErpOrderResDTO));
            if ("2000".equals(forErpOrderResDTO.getStatus())) {
                //更新订单标识信息
                XeVenOrderInfoEntity orderInfo = new XeVenOrderInfoEntity();

                if (StringUtils.isBlank(orderMark)) {
                    orderInfo.setOrderMark(VenOrderMarkEnum.SPECIALDISAMOUNT.getValue());
                } else {
                    String orderMark1 = OrderBeanUtils.removeOrderMark(orderMark.split(","), VenOrderMarkEnum.SPECIALDISAMOUNT.getValue());
                    if (StringUtils.isNotBlank(orderMark1)) {
                        orderInfo.setOrderMark(orderMark1 + "," + VenOrderMarkEnum.SPECIALDISAMOUNT.getValue());
                    } else {
                        orderInfo.setOrderMark(VenOrderMarkEnum.SPECIALDISAMOUNT.getValue());
                    }
                }

                orderInfo.setUserCode(userInfo.getUserCode());
                orderInfo.setModfiyUser(userInfo.getLoginName());
                orderInfo.setOrderId(orderForm.getOrderId());
                orderInfo.setPmtAmount(forErpOrderResDTO.getPmtAmount());
                orderInfo.setSpecialDisamount(forErpOrderResDTO.getSpecialDisamount());
                orderInfo.setTotalAmount(forErpOrderResDTO.getPayAmount());
                orderInfo.setPayAmount(forErpOrderResDTO.getPayAmount());
                orderInfo.setMainOrderId(forErpOrderResDTO.getMorderId());
                List<OrderInfoDetailDTO> orderInfoDetail = forErpOrderResDTO.getOrderInfoDetail();
                List<XeVenOrderInfoDetailEntity> orderinfoEntityList = JSON.parseArray(JSON.toJSONString(orderInfoDetail), XeVenOrderInfoDetailEntity.class);
                result = this.xeVenOrderWriteMapper.updateXeVenOrderInfo(orderInfo);
                if (result == XeConstans._XE_ONE) {
                    for (int i = 0; i < orderinfoEntityList.size(); i++) {
                        for (int j = 0; j < xeVenOrderForm.size(); j++) {
                            if (orderinfoEntityList.get(i).getItemId().equals(xeVenOrderForm.get(j).getItemId())) {
                                orderinfoEntityList.get(i).setSpecialPrice(xeVenOrderForm.get(j).getSpecPrice());
                            }
                        }
                    }
                    this.xeVenOrderWriteMapper.updateBatchOrderInfoDetail(orderinfoEntityList);
                }
            }
            log.info("修改特批优惠金额结束,时间为:{}");
            insertMqLog(ErpLogTypeEnum.erpOrderModifySpecAmount.getValue(), orderForm.getOrderId(), operContent.toString(), userInfo, requestIP, "同步前台结果:" + forErpOrderResDTO.getStatus() + "更新数据库结果为:" + result);
        } else {
            result = 1;
        }
        return result;
    }

    /**
     * 废单 在线支付创建退款单 库存回滚 同步商城  消息推送鲜易商城
     *
     * @author ruancz
     * @since 2017年6月22日 下午8:43:33
     */
    @Override
    public void judeCancelOrder(XeVenOrderInfoEntity orderInfo, ErpUserInfo userInfo) throws Exception {
        orderInfo.setUserCode(userInfo.getUserCode());
        //在线支付已支付订单 退款
        BigDecimal realRefundedAmount = new BigDecimal("0");
        if (orderInfo.getPayType() == VenOrderPayTypeEnum.ONLINE_PAY.getValue() && orderInfo.getPayStatus() == VenOrderPayStatusEnum.ALL_PAID.getValue()) {
            realRefundedAmount = insertOrderRefund(orderInfo.getOrderId(), userInfo);
        }
        //查询库存足够订单明细
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("orderId", orderInfo.getOrderId());
        map.put("userCode", userInfo.getUserCode());
        List<XeVenOrderInfoDetailEntity> orderInfoDetail = this.xeVenOrderReadMapper.getOrderDetailByParam(map);

        // 查询仓库信息 根据仓库信息进行库存回退
        if (StringUtils.isNotBlank(orderInfo.getStoreId())) {
            XeVenStoreInfoEntity storeInfo = xeVenStoreInfoReadMapper.getStoreInfoByMap(orderInfo.getStoreId(), userInfo.getUserCode());
            //更新订单仓库关联表置为删除
            XeVenOrderStoreEntity orderStoreEntity = new XeVenOrderStoreEntity();
            orderStoreEntity.setOrderId(orderInfo.getOrderId());
            orderStoreEntity.setDelFlag(VenDelEnum.YES.getValue());
            orderStoreEntity.setUserCode(userInfo.getUserCode());
            this.xeVenOrderWriteMapper.updateXeVenOrderStore(orderStoreEntity);
            //开始库存回退
            boolean result = fallbackInventory(storeInfo, orderInfoDetail, orderInfo.getStoreId(), orderInfo.getUserCode(), userInfo);
            log.info("订单号: {}库存回退结果: {}", orderInfo.getOrderId(), result == true ? "成功" : "失败");
            if (!result) {
                log.info("订单号: {},库存释放失败...", orderInfo.getOrderId());
                throw new RuntimeException(XeVenOrderMsg.FALLBACK_INVENTORY);
            }
        }
        log.info("订单号: {},结束废弃订单...", orderInfo.getOrderId());
        Map<String, Object> cancelParam = new HashMap<String, Object>();
        cancelParam.put("orderId", orderInfo.getOrderId());
        cancelParam.put("userCode", userInfo.getUserCode());
        XeVenOrderInfoEntity confirm = this.xeVenOrderWriteMapper.queryOrderInfo(cancelParam);
        OrderInfoDTO orderInfoDTO = new OrderInfoDTO();
        List<String> list = new ArrayList<String>();
        for (int i = 0; i < orderInfoDetail.size(); i++) {
            list.add(orderInfoDetail.get(i).getProSku() + "-" + orderInfoDetail.get(i).getPurchaseNum());
        }
        orderInfoDTO.setSplitOrderStatus(confirm.getSplitOrderStatus());
        orderInfoDTO.setMorderId(confirm.getMainOrderId());
        orderInfoDTO.setErpProSku((String[]) list.toArray(new String[list.size()]));
        orderInfoDTO.setOrderId(orderInfo.getOrderId());
        orderInfoDTO.setCancelRemark(orderInfo.getCancelRemark());
        orderInfoDTO.setCancelUser(userInfo.getLoginName());
        orderInfoDTO.setCancelTime(new Date());
        if (realRefundedAmount.compareTo(BigDecimal.ZERO) != 0) {
            orderInfoDTO.setRealRefundedAmount(realRefundedAmount);
        }
        log.info("取消订单入参 :{}", JSON.toJSONString(orderInfoDTO));
        BaseResponseDTO baseResponseDTO = forErpOrderIApiService.updateOrderInfo(orderInfoDTO);
        log.info("取消订单返回结果 :{}", JSON.toJSONString(baseResponseDTO));

        //废弃订单时，向收货人发送短信通知      作者：袁世林
        log.info("取消订单向收货人发送短信通知开始");
        if (baseResponseDTO != null && baseResponseDTO.getStatus().equals(XeErrorCode.PORJECT_SUCCESS)) {
            CancelOrderSender.sender.sendMessage(JSONObject.toJSONString(orderInfo));//消息通知
        }

        log.info("取消订单向收货人发送短信通知结束");


        //订单取消或实发为零取消订单推送消息到 鲜易商城
        XeVenOrderView orderView = this.xeVenOrderReadMapper.queryOrderPhoneByOrderId(orderInfo.getOrderId());
        List<XeSysMsgSendDTO> xeSysMsgSendDTOList = new ArrayList<>();
        XeSysMsgRecordDTO msgDto = new XeSysMsgRecordDTO();
        XeSysMsgSendDTO sendDTO = new XeSysMsgSendDTO();
        sendDTO.setMsgNumber(XeSmsConstans.XE_ERP_CANCEL_ORDER_SEND_MSG);
        sendDTO.setMobile(orderView.getCaPhone());
        sendDTO.setUserId(orderView.getUserId());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("orderId", orderView.getOrderId());
        jsonObject.put("morderId", orderView.getmOrderId());
        sendDTO.setJumpData(jsonObject);
        jsonObject = new JSONObject();
        jsonObject.put("orderId", orderView.getOrderId());
        sendDTO.setMsgContentParam(jsonObject);
        xeSysMsgSendDTOList.add(sendDTO);
        msgDto.setXeSysMsgSendDTOList(xeSysMsgSendDTOList);
        try {
            log.info("取消订单推送鲜易商城入参 :{}", JSON.toJSONString(msgDto));
            XeSysMsgRecordResDTO xeSysMsgRecordResDTO = xeSysMsgApiService.sendXEMsgRecords(msgDto);
            log.info("取消订单订单推送鲜易商城返回结果 :{}", JSON.toJSONString(xeSysMsgRecordResDTO));
        } catch (Exception e) {
            log.info("取消订单推送鲜易商城异常: {}", e.getMessage());
        }
        //取消订单推送销售app
        if (StringUtils.isNotBlank(orderView.getSalesmanId())) {
            try {
                XeSysMsgRecordDTO msgRecordDTO = new XeSysMsgRecordDTO();
                List<XeSysMsgSendDTO> xeSysMsgSendDTO = new ArrayList<>();
                XeSysMsgSendDTO msgSendDTO = new XeSysMsgSendDTO();
                msgSendDTO.setMsgNumber(XeSmsConstans.XE_ERP_CANCEL_ORDER_SEND_SALEMAN_MAG);
                msgSendDTO.setMobile(orderView.getSalesmanPhone());
                msgSendDTO.setUserId(orderView.getSalesmanId());
                JSONObject jsonOb = new JSONObject();
                jsonOb.put("subOrderId", orderView.getOrderId());
                jsonOb.put("userId", orderView.getUserId());//业务员标识
                jsonOb.put("orderPlat", orderView.getOrderSource());
                msgSendDTO.setJumpData(jsonOb);//跳转参数设置
                jsonOb = new JSONObject();
                jsonOb.put("loginAccount", orderView.getLoginAccount());
                if (StringUtils.isNotBlank(orderView.getUserName())) {
                    jsonOb.put("userName", orderView.getUserName());
                } else {
                    jsonOb.put("userName", "");
                }
                jsonOb.put("orderNum", orderView.getOrderId());
                msgSendDTO.setMsgContentParam(jsonOb);//消息内容参数设置
                xeSysMsgSendDTO.add(msgSendDTO);
                msgRecordDTO.setXeSysMsgSendDTOList(xeSysMsgSendDTO);
                log.info("取消订单推送销售app入参: {}", JSON.toJSONString(msgRecordDTO));
                XeSysMsgRecordResDTO xeSysMsgRecordResDTO = xeSysMsgApiService.sendMsgRecords(msgRecordDTO);
                log.info("取消订单推送销售app出参: {}", JSON.toJSONString(xeSysMsgRecordResDTO));
            } catch (Exception e) {
                log.error("取消订单推送销售app异常：{}", e);
            }
        }
    }

    /**
     * 插入退款信息
     *
     * @author ruancz
     * @since 2017年6月29日 下午5:50:47
     */
    private BigDecimal insertOrderRefund(String orderId, ErpUserInfo userInfo) {
        log.info("订单号: {},插入退款单开始...", orderId);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("orderId", orderId);
        map.put("userCode", userInfo.getUserCode());
        XeVenOrderInfoEntity orderinfoByOrderId = this.xeVenOrderReadMapper.getOrderInfo(map);
        //新建退款单
        XeVenOrderRefundEntity orderRefund = new XeVenOrderRefundEntity();
        orderRefund.setRefundCode(FinanceSeqUtil.seqUtils.createRefundCode());
        orderRefund.setUserCode(userInfo.getUserCode());
        orderRefund.setRefundSource(VenOrderRefundSourceEnum.AUTO.getValue());
        orderRefund.setRealRefundedAmount(orderinfoByOrderId.getPayAmount());
        orderRefund.setOrderId(orderId);
        orderRefund.setRefundType(VenOrderRefundTypeEnum.CANCLE.getValue());
        orderRefund.setRefundReason(VenOrderRefundReasonEnum.CANCLE.getValue());
        orderRefund.setRefundStatus(VenOrderRefundStatusEnum.PENDING.getValue()); //退款单 待退款状态
        orderRefund.setAutomaticFlag(XeConstans._XE_ONE);
        orderRefund.setCreateUser(userInfo.getLoginName());
        orderRefund.setCreateDate(new Date());
        int result = this.xeVenOrderRefundWriteMapper.insert(orderRefund);
        log.info("退款单号: {},插入结果: {}", orderRefund.getRefundCode(), result == XeConstans._XE_ONE ? "成功" : "失败");
        if (result == XeConstans._XE_ONE) {
            List<XeVenOrderInfoDetailEntity> orderInfoDetailList = orderinfoByOrderId.getOrderInfoDetailList();
            List<Map<String, Object>> orderRefundList = new ArrayList<Map<String, Object>>();
            //退款单明细
            for (int i = 0; i < orderInfoDetailList.size(); i++) {
                XeVenOrderInfoDetailEntity infoDetailEntity = orderInfoDetailList.get(i);
                Map<String, Object> orderRefundMap = new HashMap<String, Object>();
                orderRefundMap.put("refundCode", orderRefund.getRefundCode());
                orderRefundMap.put("proSku", infoDetailEntity.getProSku());
                orderRefundMap.put("buyNums", infoDetailEntity.getPurchaseNum());
                orderRefundMap.put("refundAmount", infoDetailEntity.getProPayAmount());
                orderRefundMap.put("rejectNums", infoDetailEntity.getPurchaseNum());
                orderRefundList.add(orderRefundMap);
            }
            int resultOrderDetail = this.xeVenOrderRefundDetailWriteMapper.insertAllOrderRefundDetail(orderRefundList);
            log.info("退款单号: {},插入退款明细结果: {}", orderRefund.getRefundCode(), resultOrderDetail == orderRefundList.size() ? "成功" : "失败");
        }
        log.info("订单号: {},插入退款单号: {}", orderId, orderRefund.getRefundCode());
        return orderinfoByOrderId.getPayAmount();
    }

    /**
     * 批量审核订单
     *
     * @author ruancz
     * @since 2017年6月23日 下午10:43:33
     */
    @Override
    @Transactional(value = "writeTransactionManager")
    public void updateBatchAuditOrder(List<XeVenOrderForm> formList, ErpUserInfo userInfo, String requestIP) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userCode", userInfo.getUserCode());
        map.put("list", formList);
        //订单审核同步订单收货人信息
        log.info("订单审核推送前台收货人信息开始");
        List<XeVenOrderInfoEntity> orderinfoList = this.xeVenOrderReadMapper.queryOrderInfoByParams(map);
        SplitOrderInfoDTO splitOrderInfoDTO = new SplitOrderInfoDTO();
        splitOrderInfoDTO.setOrderInfoList(JSON.parseArray(JSON.toJSONString(orderinfoList), OrderInfoDTO.class));
        for (int i = 0; i < splitOrderInfoDTO.getOrderInfoList().size(); i++) {
            splitOrderInfoDTO.getOrderInfoList().get(i).setOrderStatus(XeConstans._XE_THREE);
        }
//		log.info("推送数据为{}",JSON.toJSONString(splitOrderInfoDTO));
        BaseResponseDTO baseResponseDTO = forErpOrderIApiService.updateErpOrderInfo(splitOrderInfoDTO);
        log.info("订单审核推送前台收货人信息结束 {}", JSON.toJSONString(baseResponseDTO));
        if ("2000".equals(baseResponseDTO.getStatus())) {
            //波次号
            String checkBatchNumber = FinanceSeqUtil.seqUtils.createCheckCode();
            for (int i = 0; i < formList.size(); i++) {
                String operContent = null;
                XeVenOrderInfoEntity orderInfo = OrderBeanUtils.toXeVenOrderInfoEntity(formList.get(i));
                orderInfo.setCheckBatchNum(checkBatchNumber);
                orderInfo.setPrintBatchNum(checkBatchNumber.split("_")[1] + "_" + (formList.size()) + "_" + (i + 1));
                log.info("波次号:{},批次号 {}", orderInfo.getCheckBatchNum(), orderInfo.getPrintBatchNum());
                orderInfo.setModfiyUser(userInfo.getLoginName());
                orderInfo.setOrderStatus(VenOrderStatusEnum.WAIT_SEND.getValue());
                orderInfo.setVerifyTime(new Date());
                orderInfo.setVerifyUser(userInfo.getLoginName());
                orderInfo.setUserCode(userInfo.getUserCode());
                orderInfo.setOldOrderStatus(VenOrderStatusEnum.WAIT_CHECK.getValue());
                int infoFlag = this.xeVenOrderWriteMapper.updateXeVenOrderInfo(orderInfo);
                log.info("订单号: {},审核订单结果...", infoFlag == XeConstans._XE_ONE ? "成功" : "失败");
                if (infoFlag > XeConstans._XE_ZERO) {
                    XeVenStoreInfoEntity xeVenStoreInfo = xeVenStoreInfoReadMapper.getStoreInfoByMap(orderInfo.getStoreId(), userInfo.getUserCode());
                    //零采 订单自动创建采购单
                    if (xeVenStoreInfo.getStoreType() == VenStoreTypeEnum.ZERO_STORE.getValue()) {
                        operContent = automaticXeVenPurchOrder(orderInfo, userInfo, xeVenStoreInfo.getStoreId());
                    } else {
                        operContent = "审核通过订单【" + orderInfo.getOrderId() + "】";
                    }
                    //添加物流信息
                    XeVenOrderLogistics orderLogistics = new XeVenOrderLogistics();
                    orderLogistics.setUserCode(userInfo.getUserCode());
                    orderLogistics.setOrderId(orderInfo.getOrderId());
                    orderLogistics.setLogtsStatus(VenOrderLogisticsEnum.ORDER_CHECK.getValue());
                    updateOrderLogistics(orderLogistics, null);
                    insertMqLog(ErpLogTypeEnum.erpOrderModifyCheck.getValue(), orderInfo.getOrderId(), operContent, userInfo, requestIP, null);
                }
            }
        }
    }

    /**
     * 自动创建采购单
     *
     * @author ruancz
     * @since 2017年6月23日 下午2:15:20
     */
    private String automaticXeVenPurchOrder(XeVenOrderInfoEntity xeVenOrderInfo, ErpUserInfo userInfo, String storeId) throws Exception {
        log.info("订单号: {},开始零订单自动创建采购单...", xeVenOrderInfo.getOrderId());
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userCode", userInfo.getUserCode());
        map.put("orderId", xeVenOrderInfo.getOrderId());
        //查询订单明细
        List<XeVenOrderDetailView> orderInfoDetailList = this.xeVenOrderReadMapper.queryOrderInfoDetailByParam(map);
        //新建采购单
        XeVenPurchOrderEntity purchOrder = new XeVenPurchOrderEntity();
        this.insertPurchOrder(purchOrder, userInfo);
        purchOrder.setStoreId(storeId);
        purchOrder.setAddType(1);
        //插入采购单
        int result = this.xeVenPurchOrderWriteMapper.insertPurch(purchOrder);
        log.info("采购单号: {},插入采购单结果: {}", purchOrder.getPurchOrder(), result == XeConstans._XE_ONE ? "成功" : "失败");
        if (result == XeConstans._XE_ONE) {
            //新建采购单明细
            List<XeVenPurchOrderDetailEntity> purchOrderDetailList = getPurchOrderDetailList(orderInfoDetailList, purchOrder);

            XeVenSummaryPurchEntity summaryPurch = new XeVenSummaryPurchEntity();
            summaryPurch.setDelFLag(VenDelEnum.NO.getValue());
            summaryPurch.setOrderId(xeVenOrderInfo.getOrderId());
            summaryPurch.setOrderStatus(xeVenOrderInfo.getOrderStatus());
            summaryPurch.setPurchOrder(purchOrder.getPurchOrder());
            summaryPurch.setAddType(2);
            this.xeVenSummaryPurchService.insertXeVenSummaryPurch(summaryPurch);
            this.xeVenPurchOrderDetailWriteMapper.insertPurchProductBatch(purchOrderDetailList);
        }
        log.info("订单号: {},结束零采订单自动创建采购单,采购单号: {}", xeVenOrderInfo.getOrderId(), purchOrder.getPurchOrder());
        return "审核通过订单【" + xeVenOrderInfo.getOrderId() + "】，生成对应零采采购单【" + purchOrder.getPurchOrder() + "】。";
    }

    /**
     * 封装采购单信息
     */
    public void insertPurchOrder(XeVenPurchOrderEntity purchOrder, ErpUserInfo userInfo) {
        purchOrder.setPurchOrder(PurchSeqUtil.seqUtils.createPurchOrder());
        purchOrder.setUserCode(userInfo.getUserCode());
        purchOrder.setSignDate(new Date());
        purchOrder.setPurchType(VenPurchTypeEnum.RETAIL_BUY.getValue());
        purchOrder.setCheckStatus(VenPurchCheckEnum.WAIT_SUBMIT.getValue());
        purchOrder.setPurchStatus(VenPurchStatusEnum.WAIT_SUBMIT.getValue());
        purchOrder.setRemark(XeVenOrderMsg.PURORDER_REMARK);
        purchOrder.setCreateUser(userInfo.getLoginName());
        purchOrder.setCreateDate(new Date());
        purchOrder.setModifyUser(userInfo.getLoginName());
    }

    /**
     * 封装采购单明细信息
     */
    private List<XeVenPurchOrderDetailEntity> getPurchOrderDetailList(List<XeVenOrderDetailView> orderInfoDetailList, XeVenPurchOrderEntity purchOrder) {
        List<XeVenPurchOrderDetailEntity> purchOrderDetailList = new ArrayList<XeVenPurchOrderDetailEntity>();
        for (int i = 0; i < orderInfoDetailList.size(); i++) {
            XeVenOrderDetailView detailView = orderInfoDetailList.get(i);
            XeVenPurchOrderDetailEntity purchOrderDetail = new XeVenPurchOrderDetailEntity();
            purchOrderDetail.setPurchOrder(purchOrder.getPurchOrder());
            purchOrderDetail.setProSku(detailView.getProSku());
            purchOrderDetail.setProName(detailView.getProName());
            purchOrderDetail.setCategoryCode(detailView.getProOrgCode());
            purchOrderDetail.setCategoryName(detailView.getProOrgCodeName());
            purchOrderDetail.setProNo(detailView.getProNum());
            purchOrderDetail.setPicUrl(detailView.getProPicture());
            purchOrderDetail.setProNum(detailView.getPurchaseNum());
            purchOrderDetail.setPriceType(detailView.getPricingType());
            purchOrderDetail.setProUnit(detailView.getProUnit());
            purchOrderDetail.setSpecName(detailView.getSpecName());
            purchOrderDetail.setSpecValue(detailView.getSpecValue());
            purchOrderDetail.setFrozenFlag(detailView.getFrozenFlag());
            purchOrderDetailList.add(purchOrderDetail);
        }
        return purchOrderDetailList;
    }

    /**
     * 回退库存
     *
     * @author ruancz
     * @since 2017年6月24日 上午10:22:47
     */
    @Override
    public boolean fallbackInventory(XeVenStoreInfoEntity storeInfo, List<XeVenOrderInfoDetailEntity> orderInfoDetail, String storeId, String userCode, ErpUserInfo userInfo) throws Exception {
        log.info("订单号: {},开始库存释放...", orderInfoDetail.get(0).getOrderId());
        int result = 0;
        //判断是否记录库存
        if (storeInfo.getRecordInventoryFlag() == VenStoreInventoryFlagEnum.YES.getValue()) {
            for (int i = 0; i < orderInfoDetail.size(); i++) {
                //库存是否足够
                if (orderInfoDetail.get(i).getInventoryFlag() == VenStoreNegativeFlagEnum.YES.getValue()) {
                    XeVenStoreInventoryEntity inventory = new XeVenStoreInventoryEntity();
                    inventory.setUserCode(userCode);
                    inventory.setStoreId(storeId);
                    inventory.setProSku(orderInfoDetail.get(i).getProSku());
                    if (null != userInfo) {
                        inventory.setModifyUser(userInfo.getLoginName());
                    }
                    //释放库存
//					log.info("释放库存入参 : {}",JSON.toJSONString(orderInfoDetail));
                    inventory.setLockedInv(orderInfoDetail.get(i).getPurchaseNum().multiply(new BigDecimal(-1)));
                    int flag = this.xeVenStoreInventoryService.updateStoreInvByStoreInventoryEntity(inventory, null);
                    result += flag;
                } else {
                    result += 1;
                }
            }
        } else {
            return true;
        }
        log.info("订单号: {},结束库存释放,释放结果: {}", orderInfoDetail.get(0).getOrderId(), result == orderInfoDetail.size() ? "成功" : "失败");
        return result == orderInfoDetail.size() ? true : false;
    }

    /**
     * 更新异常订单
     *
     * @author ruancz
     * @since 2017年6月24日 上午10:22:47
     */
    @Override
    @Transactional(value = "writeTransactionManager")
    public Map<String, Object> updateExceptionOrder(List<XeVenOrderForm> formList, ErpUserInfo userInfo) throws Exception {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("inventoryFlag", XeConstans._XE_TWO);
        params.put("userCode", userInfo.getUserCode());
        for (int i = 0; i < formList.size(); i++) {
            XeVenOrderForm orderForm = formList.get(i);
            log.info("异常订单号: {},开始更新异常订单...", orderForm.getOrderId());
            params.put("orderId", orderForm.getOrderId());
            XeVenStoreInfoEntity storeInfo = this.xeVenStoreInfoReadMapper.getStoreInfoByMap(orderForm.getStoreId(), userInfo.getUserCode());
            if (null == storeInfo) {
                log.info("订单号: {}没有对应仓库,不进行处理", orderForm.getOrderId());
                continue;
            }
            List<XeVenOrderInfoDetailEntity> orderDetailList = this.xeVenOrderReadMapper.getOrderDetailByParam(params);
            //订单信息
            XeVenOrderInfoEntity venOrderInfoEntity = OrderBeanUtils.toXeVenOrderInfoEntity(orderForm);
            venOrderInfoEntity.setUserCode(userInfo.getUserCode());
            venOrderInfoEntity.setModfiyUser(userInfo.getLoginName());

            //判断
            int result = this.judeExceptionOrder(venOrderInfoEntity, storeInfo, orderDetailList);
            if (result == orderDetailList.size()) {
                venOrderInfoEntity.setOrderException(VenOrderExpFlagEnum.NO_PROBLEM.getValue());
                String orderMark = OrderBeanUtils.removeOrderMark(venOrderInfoEntity.getOrderMark().split(","), VenOrderMarkEnum.EXCEPTIONORDER.getValue());
                venOrderInfoEntity.setOrderMark(orderMark);
                venOrderInfoEntity.setOrderStatus(VenOrderStatusEnum.WAIT_CHECK.getValue());
                venOrderInfoEntity.setOldOrderException(VenOrderExpFlagEnum.PROBLEM.getValue());
                int orderInfoFlag = this.xeVenOrderWriteMapper.updateXeVenOrderInfo(venOrderInfoEntity);
                if (XeConstans._XE_ZERO == orderInfoFlag) {
                    throw new RuntimeException("this order is not exception order");
                }
				/*if (orderInfoFlag > 0) {
					for (int j = 0; j < orderDetailList.size(); j++) {
						//将库存不足订单明细置为正常状态
						orderDetailList.get(j).setUserCode(userInfo.getUserCode());
						orderDetailList.get(j).setInventoryFlag(XeConstans._XE_ONE);
						orderDetailList.get(j).setModifyUser(venOrderInfoEntity.getModfiyUser());
						this.xeVenOrderWriteMapper.updateXeVenOrderInfoDetail(orderDetailList.get(j));
					}
				}*/
            }
            log.info("异常订单号: {},结束更新异常订单,更新结果: {}", orderForm.getOrderId(), result == orderDetailList.size() ? "成功" : "失败");
        }
        resultMap.put(XeVenBusConstans.CODE, XeVenBusConstans.BUSSINESS_SUCCESS);
        resultMap.put(XeVenBusConstans.MSG, XeVenOrderMsg.UPDATE_EXCEPTION_ORDER);
        return resultMap;
    }

    /**
     * 取消审核订单
     *
     * @author ruancz
     * @since 2017年6月24日 上午10:22:47
     */
    @Override
    @Transactional(value = "writeTransactionManager")
    public Map<String, Object> updateUnBatchAuditOrder(List<XeVenOrderForm> formList, ErpUserInfo userInfo, String requestIP) throws Exception {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put(XeVenBusConstans.CODE, XeVenBusConstans.BUSSINESS_SUCCESS);
        Map<String, Object> params = new HashMap<String, Object>();
        //记录取消订单id
        int result = 0;
        for (int i = 0; i < formList.size(); i++) {
            XeVenOrderInfoEntity orderInfo = OrderBeanUtils.toXeVenOrderInfoEntity(formList.get(i));
            log.info("订单号: {},开始取消审核订单...", orderInfo.getOrderId());
            orderInfo.setOrderStatus(VenOrderStatusEnum.WAIT_CHECK.getValue());
            orderInfo.setUserCode(userInfo.getUserCode());
            orderInfo.setModfiyUser(userInfo.getLoginName());
            orderInfo.setOldOrderStatus(VenOrderStatusEnum.WAIT_SEND.getValue());
            XeVenStoreInfoEntity venStoreInfo = this.xeVenStoreInfoReadMapper.getStoreInfoByMap(orderInfo.getStoreId(), userInfo.getUserCode());
            int infoFlag = this.xeVenOrderWriteMapper.updateXeVenOrderInfo(orderInfo);
            result += infoFlag;
            if (infoFlag == XeConstans._XE_ZERO) {
                continue;
            }
            unBatchOrder(orderInfo, venStoreInfo, params);
            log.info("订单号: {},结束取消审核订单...", orderInfo.getOrderId());
            //添加物流信息
            XeVenOrderLogistics orderLogistics = new XeVenOrderLogistics();
            orderLogistics.setUserCode(userInfo.getUserCode());
            orderLogistics.setOrderId(orderInfo.getOrderId());
            orderLogistics.setLogtsStatus(VenOrderLogisticsEnum.STORE_IN.getValue());
            orderLogistics.setCreateUser(userInfo.getLoginName());
            deleteOrderLogistics(orderLogistics, venStoreInfo.getStoreName());
            insertMqLog(ErpLogTypeEnum.erpOrderModifyUnCheck.getValue(), orderInfo.getOrderId(), "取消订单【" + orderInfo.getOrderId() + "】的审核。", userInfo, requestIP, null);
        }
        resultMap.put(XeVenBusConstans.MSG, "订单取消审核成功" + result + "条，失败" + (formList.size() - result) + "条。");
        return resultMap;

    }

    /**
     * 零采分拨订单取消审核/实发为零
     */
    private void unBatchOrder(XeVenOrderInfoEntity orderInfo, XeVenStoreInfoEntity venStoreInfo, Map<String, Object> params) throws Exception {
        params.put("orderId", orderInfo.getOrderId());
        params.put("orderStatus", VenOrderStatusEnum.WAIT_SEND.getValue());
        params.put("delFlag", VenDelEnum.NO.getValue());
        //查询采购单关联所有待发货的订单
        List<Map<String, Object>> resultList = this.xeVenSummaryPurchService.queryOrderListByParams(params);
        //零采订单
        if (VenStoreTypeEnum.ZERO_STORE.getValue() == venStoreInfo.getStoreType()) {
            cancelPurcherOrder(orderInfo, params, resultList, null);
        }

        /**
         * 分拨订单
         * 手动创建分拨采购单
         * 1 当前订单关联一个采购单且当前采购单关联多个订单(逻辑同自动创建分拨采购单一样)
         * 2 当前订单关联多个采购单 判断多个采购单对应订单状态 来 断定采购单是否完成或作废
         */
        if (VenStoreTypeEnum.ALLOCATE_STORE.getValue() == venStoreInfo.getStoreType()) {
            List<String> purchOrder = resultList.stream()
                    .map(key -> key.get("purchOrder").toString()).distinct().collect(toList());
            if (purchOrder.size() == XeConstans._XE_ONE) {
                cancelPurchOrder(orderInfo, params, resultList);
            } else {

                params.remove("orderId");
                params.remove("orderStatus");
                params.put("purchOrderList", purchOrder);
                List<Map<String, Object>> summaryPurchList = xeVenSummaryPurchService.queryOrderListByParams(params);
                //根据采购单号（过滤掉当前订单）进行分组  key=采购单号 value=采购单对应订单
                Map<String, List<Map<String, Object>>> purchOrderGroup = summaryPurchList
                        .stream().filter(purch -> !purch.get("orderId").equals(orderInfo.getOrderId()))
                        .collect(groupingBy(key -> key.get("purchOrder").toString()));
                //订单对应多个采购单并且多个采购单对应的订单只有当前订单 取消关联关系
                if (purchOrderGroup.size() == 0) {
                    Map<String, Object> param = new HashMap<String, Object>();
                    param.put("delFlag", VenDelEnum.YES.getValue());
                    param.put("orderId", orderInfo.getOrderId());
                    this.xeVenSummaryPurchService.updateXeVenSummaryPurch(param);
                   /* dcj
                    * for (int i = 0; i < purchOrder.size(); i++) {
                        XeVenPurchForm purchForm = new XeVenPurchForm();
                        purchForm.setUserCode(orderInfo.getUserCode());
                        purchForm.setPurchStatus(VenPurchStatusEnum.CANCELED.getValue());
                        purchForm.setOrderId(orderInfo.getOrderId());
                        purchForm.setPurchOrder(purchOrder.get(i));
                        this.xeVenPurchService.updatePurchOrder(purchForm);
                    }*/
                } else {
                    Map<String, List<Map<String, Object>>> purchOrderGroups = summaryPurchList
                            .stream().collect(groupingBy(key -> key.get("purchOrder").toString()));
                    for (int i = 0; i < purchOrder.size(); i++) {
                        String purchOrderId = purchOrder.get(i);
                        //采购单仅关联当前订单  取消关联关系 
                        if (purchOrderGroups.get(purchOrderId).size() == XeConstans._XE_ONE) {
                            params.put("purchOrder", purchOrderId);
                            params.put("delFlag", VenDelEnum.YES.getValue());
                            params.put("orderId", orderInfo.getOrderId());
                            this.xeVenSummaryPurchService.updateXeVenSummaryPurch(params);
                        } else {//采购单仅关联其他订单
                            //根据订单状态进行分组 key订单状态 value=当前状态下所有订单
                            Map<String, List<Map<String, Object>>> orderStatusGroup = purchOrderGroups.get(purchOrderId).stream()
                                    .filter(purch -> !purch.get("orderId").equals(orderInfo.getOrderId()))
                                    .collect(groupingBy(key -> key.get("orderStatus").toString()));
                            //订单状态 ：1 已完成 2 已发货 3待发货
                            if (orderStatusGroup.size() != 0) {
                                params.put("delFlag", VenDelEnum.YES.getValue());
                                params.put("orderId", orderInfo.getOrderId());
                                params.put("purchOrder", purchOrderId);
                                this.xeVenSummaryPurchService.updateXeVenSummaryPurch(params);

                            /*//当前采购单关联订单只有待发货订单  取消关联关系
                            if (orderStatusGroup.containsKey("3") && !orderStatusGroup.containsKey("1") && !orderStatusGroup.containsKey("2")) {
                            }*/
                                if (purchOrderGroups.get(purchOrderId).stream().filter(p -> p.get("addType").equals(VenOrderSumPurAddTypeEnum.AUTOMATIC.getValue())).count() > 0) {
                                    //当前采购单没有待发货订单 只有已发货和已完成订单 取消关联关系 采购单异常完成 生成付款单
                                    if (!orderStatusGroup.containsKey("3") && (orderStatusGroup.containsKey("1") || orderStatusGroup.containsKey("2"))) {
                                        XeVenPurchForm purchForm = new XeVenPurchForm();
                                        purchForm.setUserCode(orderInfo.getUserCode());
                                        purchForm.setPurchStatus(VenPurchStatusEnum.ABNORMAL_COMPLETE.getValue());
                                        purchForm.setPurchOrder(purchOrderId);
                                        purchForm.setCheckStatus(6);
                                        purchForm.setModifyUser(orderInfo.getModfiyUser());
                                        this.xeVenPurchService.finishPurchOrder(purchForm);
                                    }
                                }

                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 分拨订单取消  取消关联关系
     * 如果只有一条 说明当前汇总采购单 取消审核的是最后一条订单
     * 则当前采购单对应的订单是否有已经发货的订单  如果有  采购单置为异常完成  没有则置为作废 并取消关联关系
     * <p>
     * 如果有多条 取消关联关系即可
     */
    private void cancelPurchOrder(XeVenOrderInfoEntity orderInfo, Map<String, Object> params, List<Map<String, Object>> resultList) throws Exception {

        if (resultList.size() == XeConstans._XE_ONE) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("orderId", orderInfo.getOrderId());
            map.put("delFlag", VenDelEnum.NO.getValue());
            //查询订单关联的所有采购单所关联的所有订单
            List<Map<String, Object>> mapList = this.xeVenSummaryPurchService.queryOrderListByParams(map);
            boolean flag = true;
            for (int i = 0; i < mapList.size(); i++) {
                Integer orderStatus = Integer.parseInt(mapList.get(i).get("orderStatus").toString());
                if (orderStatus == VenOrderStatusEnum.FINISH.getValue() || orderStatus == VenOrderStatusEnum.SEND.getValue()) {
                    flag = false;
                    break;
                }
            }
            params.put("delFlag", VenDelEnum.YES.getValue());
            //取消订单和采购单的关联关系
            this.xeVenSummaryPurchService.updateXeVenSummaryPurch(params);
            //如果采购单为手动生成的，不需要进行采购单的自动完成或废弃
            if (resultList.get(0).get("addType").equals(VenOrderSumPurAddTypeEnum.AUTOMATIC.getValue())) {
                if (flag) {
                    XeVenPurchForm purchForm = new XeVenPurchForm();
                    purchForm.setUserCode(orderInfo.getUserCode());
                    purchForm.setPurchStatus(VenPurchStatusEnum.CANCELED.getValue());
                    purchForm.setOrderId(orderInfo.getOrderId());
                    purchForm.setPurchOrder(mapList.get(0).get("purchOrder").toString());
                    this.xeVenPurchService.updatePurchOrder(purchForm);
                } else if (!flag) {
                    //当前订单为采购单最后一条 采购单异常完成 创建应付款单
                    XeVenPurchForm purchForm = new XeVenPurchForm();
                    purchForm.setUserCode(orderInfo.getUserCode());
                    purchForm.setPurchStatus(VenPurchStatusEnum.ABNORMAL_COMPLETE.getValue());
                    purchForm.setPurchOrder(mapList.get(0).get("purchOrder").toString());
                    purchForm.setCheckStatus(6);
                    purchForm.setModifyUser(orderInfo.getModfiyUser());
                    this.xeVenPurchService.finishPurchOrder(purchForm);
                    //当前汇总采购最后一条订单取消审核或实发为零  生成付款单

                }
            }

        } else {
            params.remove("orderStatus");
            params.put("delFlag", VenDelEnum.YES.getValue());
            this.xeVenSummaryPurchService.updateXeVenSummaryPurch(params);
        }
    }

    /**
     * 订单取消审核/实发为零  取消订单关联采购单， 作废采购单
     */
    private void cancelPurcherOrder(XeVenOrderInfoEntity orderInfo, Map<String, Object> params, List<Map<String, Object>> resultList, String purchOrder) throws Exception {
        params.put("delFlag", VenDelEnum.YES.getValue());
        params.put("orderId", orderInfo.getOrderId());
        this.xeVenSummaryPurchService.updateXeVenSummaryPurch(params);
        XeVenPurchForm purchForm = new XeVenPurchForm();
        purchForm.setUserCode(orderInfo.getUserCode());
        purchForm.setPurchStatus(VenPurchStatusEnum.CANCELED.getValue());
        purchForm.setOrderId(orderInfo.getOrderId());
        if (null == purchOrder) {
            purchForm.setPurchOrder(resultList.get(0).get("purchOrder").toString());
        } else {
            purchForm.setPurchOrder(purchOrder);
        }

        this.xeVenPurchService.updatePurchOrder(purchForm);
    }


    /**
     * 订单发货更新订单状态接口
     *
     * @author 李贝贝
     * @since 2017年7月1日 下午1:58:58
     */
    @Override
    public int updateXeVenOrder(XeVenOrderInfoEntity orderInfoEntity) throws Exception {
        return xeVenOrderWriteMapper.updateXeVenOrderInfo(orderInfoEntity);
    }

    /**
     * 查询订单明细接口
     *
     * @author ruancz
     * @since 2017年7月4日 上午11:51:50
     */
    @Override
    public List<XeVenOrderInfoDetailEntity> getOrderDetailByParam(Map<String, Object> params) {
        return this.xeVenOrderReadMapper.getOrderDetailByParam(params);
    }

    /**
     * 批量修改订单实发接口
     *
     * @author 阮承志
     * @since 2017年7月3日 下午10:58:58
     */
    @Override
    @Transactional(value = "writeTransactionManager")
    public Map<String, Object> updateOrderRealSendNum(ErpUserInfo userInfo, List<XeVenSplitOrderForm> xeVenSplitOrderForm, String requestIP) throws Exception {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put(XeVenBusConstans.CODE, XeVenBusConstans.BUSSINESS_SUCCESS);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("userCode", userInfo.getUserCode());

        //记录采购财务审核不通过或修改订单失败的订单
        List<String> errorList = new ArrayList();
        List<String> resultErrList = new ArrayList();
        List<String> shipTypeErrList = new ArrayList();
        for (int i = 0; i < xeVenSplitOrderForm.size(); i++) {

            XeVenSplitOrderForm orderForm = xeVenSplitOrderForm.get(i);
            String orderId = orderForm.getOrderId();
            log.info("订单号: {},开始修改实发数量...", orderId);
            XeVenStoreInfoEntity storeInfo = this.xeVenStoreInfoReadMapper.getStoreInfoByMap(orderForm.getStoreId(), userInfo.getUserCode());
            //判断是否零采分拨订单
            if (VenStoreTypeEnum.ZERO_STORE.getValue().equals(storeInfo.getStoreType()) || VenStoreTypeEnum.ALLOCATE_STORE.getValue().equals(storeInfo.getStoreType())) {
                // 调接口判断对应采购单是否财审审核通过
                XeVenPurchForm xeVenPurchForm = new XeVenPurchForm();
                xeVenPurchForm.setUserCode(userInfo.getUserCode());
                xeVenPurchForm.setOrderId(orderForm.getOrderId());
                // 要重新改接口
                List<XeVenPurchView> purchViewList = xeVenPurchService.queryPurchList(xeVenPurchForm);
                if (null == purchViewList) {
                    log.info("订单号: {} 没有创建汇总采购单", orderForm.getOrderId());
                    resultErrList.add(orderForm.getOrderId());
                    continue;
                } else if (!(purchViewList.get(0).getCheckStatus().equals(VenPurchCheckEnum.CHECKED.getValue()))) {
                    log.info("订单号: {},财务审核不通过不可以修改实发,采购单号为: {}", orderForm.getOrderId(), purchViewList.get(0).getPurchOrder());
                    //审核不通过  则不能修改实发
                    resultErrList.add(orderForm.getOrderId());
                    continue;
                }
            }
            //判断订单的发货方式及是否已经派车
            if (!checkShipType(orderId)) {
                shipTypeErrList.add(orderId);
                continue;
            }
            //更新订单和订单明细
            XeVenOrderInfoEntity orderInfo = new XeVenOrderInfoEntity();
            orderInfo.setOrderId(orderForm.getOrderId());
            orderInfo.setStoreId(orderForm.getStoreId());
            orderInfo.setStoreName(storeInfo.getStoreName());
            orderInfo.setConfirmSendNum(VenOrderConfirmEnum.YES.getValue());
            orderInfo.setDifferenceAmount(new BigDecimal("0"));
            orderInfo.setEpayAmount(new BigDecimal("0"));
            orderInfo.setModfiyUser(userInfo.getLoginName());
            orderInfo.setUserCode(userInfo.getUserCode());
            int resultFlag = this.xeVenOrderWriteMapper.updateXeVenOrderInfo(orderInfo);
            if (resultFlag == XeConstans._XE_ZERO) {
                log.info("订单号: {}修改订单确认实发失败", orderForm.getOrderId());
                errorList.add(orderForm.getOrderId());
                continue;
            }
            this.xeVenOrderWriteMapper.updateBatchOrderInfoDetailByOrderId(orderInfo.getOrderId());
            params.put("orderId", orderForm.getOrderId());
            XeVenOrderInfoEntity orderInfoEntity = this.xeVenOrderReadMapper.getOrderInfo(params);
            if (StringUtils.isBlank(orderInfoEntity.getStoreName())) {
                orderInfoEntity.setStoreName(storeInfo.getStoreName());
            }
            //货到付款创单
            if (orderForm.getPayType().equals(VenOrderPayTypeEnum.ARRIVE_PAY.getValue())) {
                //货到付款创单
                String result = this.xeVenEpayService.insertPostOrder(orderForm.getOrderId(), orderInfoEntity.getPayAmount().toString(), orderInfoEntity.getEpayAccount());
				/*if (StringUtils.isNotBlank(result)) {
					JSONObject jsonObject = JSON.parseObject(result);
					if (!(jsonObject.get("resultCode").toString().equals("0000"))) {
						throw new  RuntimeException("insertPostOrder fail");
					}
				}*/
            }
            //仓库接入TMS  实发推送TMS
            if (storeInfo.getTmsStatus().equals(VenStoreTmsStatusEnum.YES.getValue())) {
                //将实发推送供应链
                this.supplyChainService.insertSupplyChainOrder(orderInfoEntity, null, requestIP, userInfo);
            }
            XeVenOrderLogistics orderLogistics = new XeVenOrderLogistics();
            orderLogistics.setUserCode(userInfo.getUserCode());
            orderLogistics.setOrderId(orderForm.getOrderId());
            orderLogistics.setLogtsStatus(VenOrderLogisticsEnum.WAIT_SEND.getValue());
            updateOrderLogistics(orderLogistics, null);
            log.info("订单号: {},结束修改实发数量...", orderForm.getOrderId());

            insertMqLog(ErpLogTypeEnum.erpOrderModifyRealSendNum.getValue(), orderForm.getOrderId(), "修改订单号" + orderForm.getOrderId() + "实发量为订购量", userInfo, requestIP, null);
        }
        StringBuilder sb = new StringBuilder("批量确认实发成功");
        if (resultErrList.size() > 0) {
            sb.append(resultErrList.toString() + "失败原因：订单关联的采购单未财务审核通过。\n");
        }
        if (shipTypeErrList.size() > 0) {
            sb.append(shipTypeErrList.toString() + "失败原因：" + XeVenOrderMsg.REAL_SEND_NOT_SEND_CAR_ERROR + "\n");
        }
        if (errorList.size() > 0) {
            sb.append(errorList.toString() + "失败原因：其他。");
        }
        resultMap.put(XeVenBusConstans.MSG, sb.toString());
        return resultMap;
    }

    /**
     * 锁单/解锁接口
     *
     * @return void
     * @author ruancz
     * @since 2017年7月6日 下午5:21:26
     */
    @Override
    @Transactional(value = "writeTransactionManager")
    public int updateLockOrderInfo(List<XeVenOrderForm> orderForm, ErpUserInfo userInfo, String flag) {
        List<XeVenOrderInfoEntity> orderInfoList = OrderBeanUtils.toXeVenOrderInfoEntity(orderForm, userInfo, flag);
        return this.xeVenOrderWriteMapper.updateBatchOrderInfo(orderInfoList);
    }

    /**
     * 修改订单运费金额
     *
     * @author ruancz
     * @since 2017年7月7日 下午4:29:57
     */
    @Override
    @Transactional(value = "writeTransactionManager")
    public int updateFreAmount(XeVenOrderForm xeVenOrderForm, ErpUserInfo userInfo, String requestIP) {

        // 调用给前台接口同步订单运费
        String spanId = UUID.randomUUID().toString().replaceAll("-", "");
        SendMonitorDTO clientSend = MonitorUtil.monitorUtil.controllerRecv(spanId, xeVenOrderForm.getOrderId(), JSON.toJSONString(xeVenOrderForm));

        ForErpOrderDTO erpOrderDTO = new ForErpOrderDTO();
        erpOrderDTO.setOrderId(xeVenOrderForm.getOrderId());
        erpOrderDTO.setFreAmount(xeVenOrderForm.getFreAmount());
        erpOrderDTO.setUserId(xeVenOrderForm.getUserId());
        erpOrderDTO.setModfiyUser(userInfo.getLoginName());
        erpOrderDTO.setTraceId(clientSend.getTraceId());
        erpOrderDTO.setSpanId(spanId);
        erpOrderDTO.setKey(xeVenOrderForm.getOrderId());
        log.info("修改运费金额同步入参 :{}", JSON.toJSONString(erpOrderDTO));
        ForErpOrderResDTO forErpOrderResDTO = null;
        int result = 0;
        try {
            forErpOrderResDTO = forErpOrderIApiService.modifyOrderFreight(erpOrderDTO);
            log.info("修改运费金额同步出参 :{}", JSON.toJSONString(forErpOrderResDTO));
            result = 0;
            if ("2000".equals(forErpOrderResDTO.getStatus())) {
                MonitorUtil.monitorUtil.controllerSend(spanId, JSON.toJSONString(forErpOrderResDTO), true);
                XeVenOrderInfoEntity orderInfoEntity = new XeVenOrderInfoEntity();
                orderInfoEntity.setOrderId(xeVenOrderForm.getOrderId());
                orderInfoEntity.setFreAmount(xeVenOrderForm.getFreAmount());
                orderInfoEntity.setModfiyUser(userInfo.getLoginName());
                orderInfoEntity.setPayAmount(forErpOrderResDTO.getPayAmount());
                orderInfoEntity.setMainOrderId(forErpOrderResDTO.getMorderId());
                if (null == xeVenOrderForm.getOrderMark()) {
                    orderInfoEntity.setOrderMark(VenOrderMarkEnum.FREAMOUNT.getValue());
                } else {
                    String orderMark = OrderBeanUtils.removeOrderMark(xeVenOrderForm.getOrderMark().split(","), VenOrderMarkEnum.FREAMOUNT.getValue());
                    if (StringUtils.isNotBlank(orderMark)) {
                        orderInfoEntity.setOrderMark(orderMark + "," + VenOrderMarkEnum.FREAMOUNT.getValue());
                    } else {
                        orderInfoEntity.setOrderMark(VenOrderMarkEnum.FREAMOUNT.getValue());
                    }
                }
                result = this.xeVenOrderWriteMapper.updateXeVenOrderInfo(orderInfoEntity);
            } else {
                MonitorUtil.monitorUtil.controllerSend(spanId, JSON.toJSONString(forErpOrderResDTO.getMsg()), false);
            }
        } catch (Exception e) {
            log.info("推送前台运费异常");
            MonitorUtil.monitorUtil.controllerSend(spanId, "推送前台运费异常", false);
        }
        this.insertMqLog(ErpLogTypeEnum.erpOrderModifyFreAmount.getValue(), xeVenOrderForm.getOrderId(), "修改订单" + xeVenOrderForm.getOrderId() + "的运费金额为¥" + xeVenOrderForm.getFreAmount() + "。", userInfo, requestIP, "同步前台结果为" + forErpOrderResDTO.getStatus());
        return result;
    }

    /**
     * 修改仓库
     *
     * @author ruancz
     * @since 2017年7月7日 下午4:29:57
     */
    @Override
    @Transactional(value = "writeTransactionManager")
    public Map<String, Object> updateOrderStore(List<XeVenOrderForm> formList, ErpUserInfo userInfo, String requestIP) throws Exception {
        //封装返回信息
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put(XeVenBusConstans.CODE, XeVenBusConstans.BUSSINESS_SUCCESS);
        resultMap.put(XeVenBusConstans.MSG, "修改仓库成功!");
        //记录异常订单
        int fail = 0;
        //封装查询条件
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userCode", userInfo.getUserCode());
        for (int i = 0; i < formList.size(); i++) {
            XeVenOrderForm orderForm = formList.get(i);
            log.info("订单号: {}开始重新分仓,仓库id: {}", orderForm.getOrderId(), orderForm.getStoreId());
            XeVenOrderInfoEntity venOrderInfoEntity = new XeVenOrderInfoEntity();
            venOrderInfoEntity.setOrderId(orderForm.getOrderId());
            venOrderInfoEntity.setStoreId(orderForm.getStoreId());
            venOrderInfoEntity.setOrderMark(orderForm.getOrderMark());
            venOrderInfoEntity.setModfiyUser(userInfo.getLoginName());
            venOrderInfoEntity.setUserCode(userInfo.getUserCode());
            venOrderInfoEntity.setOldOrderStatus(VenOrderStatusEnum.WAIT_DIS.getValue());
            //更新仓库操作且 重新分仓跟原来仓库一样
            map.put("orderId", venOrderInfoEntity.getOrderId());
            XeVenOrderStoreEntity orderStore = this.xeVenOrderReadMapper.getOrderStoreByOrderId(map);
            if (null != orderStore && orderStore.getStoreId().equals(venOrderInfoEntity.getStoreId())) {
                log.info("订单号: {}重新分仓和原仓库一样", orderForm.getOrderId());
                continue;
            } else {
                //查询订单明细
                List<XeVenOrderInfoDetailEntity> orderInfoDetailList = this.xeVenOrderReadMapper.getOrderDetailByParam(map);
                //如果原订单已分仓 原仓库释放库存  未分仓则直接分仓
                boolean fallbackInventory = true;
                if (null != orderStore) {
                    venOrderInfoEntity.setOldOrderStatus(VenOrderStatusEnum.WAIT_CHECK.getValue());
                    //查询仓库信息 进行库存回退等操作
                    XeVenStoreInfoEntity oldStoreInfo = xeVenStoreInfoReadMapper.getStoreInfoByMap(orderStore.getStoreId(), userInfo.getUserCode());
                    fallbackInventory = fallbackInventory(oldStoreInfo, orderInfoDetailList, oldStoreInfo.getStoreId(), userInfo.getUserCode(), userInfo);
                    log.info("订单号: {}在原仓库: {}释放库存结果: {}", orderForm.getOrderId(), orderStore.getStoreId(), fallbackInventory == true ? "成功" : "失败");
                }
                XeVenOrderStoreEntity orderStoreEntity = new XeVenOrderStoreEntity();
                orderStoreEntity.setStoreId(venOrderInfoEntity.getStoreId());
                orderStoreEntity.setDelFlag(VenDelEnum.NO.getValue());
                orderStoreEntity.setUserCode(userInfo.getUserCode());
                orderStoreEntity.setOrderId(orderForm.getOrderId());
                //库存释放成功
                if (fallbackInventory) {
                    XeVenStoreInfoEntity newStoreInfo = xeVenStoreInfoReadMapper.getStoreInfoByMap(venOrderInfoEntity.getStoreId(), userInfo.getUserCode());
                    //判断是否是异常订单以及分仓是否成功
                    int result = judeExceptionOrder(venOrderInfoEntity, newStoreInfo, orderInfoDetailList);
                    log.info("订单号: {}重新占用库存结果: {}", orderForm.getOrderId(), result == orderInfoDetailList.size() ? "成功" : "失败");
                    // 该订单库存足够 重新分仓站库存     原仓库释放库存
                    venOrderInfoEntity.setOrderStatus(VenOrderStatusEnum.WAIT_CHECK.getValue());


                    if (result == orderInfoDetailList.size()) {
                        if (StringUtils.isNotBlank(venOrderInfoEntity.getOrderMark())) {
                            String orderMark = OrderBeanUtils.removeOrderMark(venOrderInfoEntity.getOrderMark().split(","), VenOrderMarkEnum.EXCEPTIONORDER.getValue());
                            venOrderInfoEntity.setOrderMark(orderMark);
                        }
                        venOrderInfoEntity.setOrderException(VenOrderExpFlagEnum.NO_PROBLEM.getValue());
                    } else {
                        if (null == venOrderInfoEntity.getOrderMark()) {
                            venOrderInfoEntity.setOrderMark(VenOrderMarkEnum.EXCEPTIONORDER.getValue());
                        } else {
                            String orderMark = OrderBeanUtils.removeOrderMark(venOrderInfoEntity.getOrderMark().split(","), VenOrderMarkEnum.EXCEPTIONORDER.getValue());
                            if (StringUtils.isNotBlank(orderMark)) {
                                venOrderInfoEntity.setOrderMark(orderMark + "," + VenOrderMarkEnum.EXCEPTIONORDER.getValue());
                            } else {
                                venOrderInfoEntity.setOrderMark(VenOrderMarkEnum.EXCEPTIONORDER.getValue());
                            }
                        }
                        //异常订单
                        venOrderInfoEntity.setOrderException(VenOrderExpFlagEnum.PROBLEM.getValue());

                    }
                    int infoFlag = this.xeVenOrderWriteMapper.updateXeVenOrderInfo(venOrderInfoEntity);
                    if (infoFlag == XeConstans._XE_ONE) {
                        //未分仓添加物流信息  否则修改仓库信息
                        if (null == orderStore) {
                            orderStoreEntity.setCreateUser(userInfo.getLoginName());
                            orderStoreEntity.setCreateDate(new Date());
                            this.xeVenOrderWriteMapper.insertXeVenOrderStore(orderStoreEntity);
                            insertOrderLogistics(userInfo, orderForm.getOrderId(), newStoreInfo.getStoreName());
                        } else {
                            orderStoreEntity.setModifyUser(userInfo.getLoginName());
                            orderStoreEntity.setOldStoreId(orderStore.getStoreId());
                            this.xeVenOrderWriteMapper.updateXeVenOrderStore(orderStoreEntity);
                            XeVenOrderLogistics orderLogistics = new XeVenOrderLogistics();
                            orderLogistics.setUserCode(userInfo.getUserCode());
                            orderLogistics.setOrderId(venOrderInfoEntity.getOrderId());
                            orderLogistics.setLogtsStatus(VenOrderLogisticsEnum.STORE_IN.getValue());
                            updateOrderLogistics(orderLogistics, newStoreInfo.getStoreName());
                        }
                    } else {
                        throw new RuntimeException("this order status change");
                    }
                    this.insertMqLog(ErpLogTypeEnum.erpOrderModifyStore.getValue(), orderForm.getOrderId(), "修改订单" + orderForm.getOrderId() + "的发货仓库为" + newStoreInfo.getStoreName() + "。", userInfo, requestIP, null);
                } else {
                    fail += 1;
                    continue;
                }
            }
            log.info("订单号: {}结束重新分仓,仓库id: {}", orderForm.getOrderId(), orderForm.getStoreId());
        }
        if (formList.size() > 1) {
            if (fail == 0) {
                resultMap.put(XeVenBusConstans.MSG, "修改仓库成功!");
            } else {
                resultMap.put(XeVenBusConstans.CODE, XeVenBusConstans.BUSSINESS_ERROR);
                resultMap.put(XeVenBusConstans.MSG, "修改仓库成功" + (formList.size() - fail) + "条，失败" + fail + "条！" + "失败原因：原有仓库库存释放失败，请重新操作。");
            }
        }
        if (fail == 1 && formList.size() == 1) {
            resultMap.put(XeVenBusConstans.CODE, XeVenBusConstans.BUSSINESS_ERROR);
            resultMap.put(XeVenBusConstans.MSG, "修改仓库失败。失败原因：原有仓库库存释放失败，请重新操作。");
        }
        return resultMap;
    }

    /**
     * 添加物流信息
     */
    @Override
    public void insertOrderLogistics(ErpUserInfo userInfo, String orderId, String storeName) throws Exception {
        XeVenOrderLogistics orderLogistics = new XeVenOrderLogistics();
        orderLogistics.setLogtsStatus(VenOrderLogisticsEnum.STORE_IN.getValue());
        orderLogistics.setLogtsCode(StoreHouseSeqUtil.seqUtils.createLogisticsCode());
        orderLogistics.setUserCode(userInfo.getUserCode());
        orderLogistics.setOrderId(orderId);
        orderLogistics.setCreateUser(userInfo.getLoginName());
        XeVenOrderLogisticsDetail orderLogisticsDetail = new XeVenOrderLogisticsDetail();
        orderLogisticsDetail.setCreateUser(userInfo.getLoginName());
        orderLogisticsDetail.setUserCode(userInfo.getUserCode());
        orderLogisticsDetail.setLogtsCode(orderLogistics.getLogtsCode());
        orderLogisticsDetail.setLogtsStatus(orderLogistics.getLogtsStatus());
        orderLogisticsDetail.setLogtsDesc(XeVenOrderMsg.getLogtsNodeMsg(XeConstans._XE_ONE, storeName, null, null));
        this.xeVenOrderLogisticsService.insertLogistics(orderLogistics);
        this.xeVenOrderLogisticsService.insertLogisticsDetail(orderLogisticsDetail);
    }

    /**
     * 修改物流信息   查询物流编号 去更新信息
     */
    @Override
    public int updateOrderLogistics(XeVenOrderLogistics orderLogistics, String storeName) {
        XeVenOrderLogisticsForm orderLogisticsForm = new XeVenOrderLogisticsForm();
        orderLogisticsForm.setUserCode(orderLogistics.getUserCode());
        orderLogisticsForm.setOrderId(orderLogistics.getOrderId());
        List<XeVenOrderLogistics> orderLogisticsList = this.xeVenOrderLogisticsService.selectLogisticsList(orderLogisticsForm);
        if (null == orderLogisticsList || orderLogisticsList.size() == XeConstans._XE_ZERO) {
            return 0;
        }
        orderLogistics.setLogtsCode(orderLogisticsList.get(XeConstans._XE_ZERO).getLogtsCode());
        XeVenOrderLogisticsDetail orderLogisticsDetail = new XeVenOrderLogisticsDetail();
        orderLogisticsDetail.setUserCode(orderLogistics.getUserCode());
        orderLogisticsDetail.setLogtsCode(orderLogistics.getLogtsCode());
        orderLogisticsDetail.setLogtsStatus(orderLogistics.getLogtsStatus());
        orderLogisticsDetail.setCreateDate(new Date());
        orderLogisticsDetail.setLogtsDesc(XeVenOrderMsg.getLogtsNodeMsg(orderLogistics.getLogtsStatus(), storeName, null, orderLogistics.getSendCarMsg()));
        int flag = this.xeVenOrderLogisticsService.updateLogisticsByLogtsCode(orderLogistics);
        if (flag == XeConstans._XE_ONE) {
            if (StringUtils.isBlank(storeName)) {
                this.xeVenOrderLogisticsService.insertLogisticsDetail(orderLogisticsDetail);
				/*//审核通过 同时插入备货物流记录
				if (VenOrderLogisticsEnum.ORDER_CHECK.getValue() == orderLogistics.getLogtsStatus()) {
					XeVenOrderLogisticsDetail orderLogisticsDetail2 = JSON.parseObject(JSON.toJSONString(orderLogisticsDetail),XeVenOrderLogisticsDetail.class);
					orderLogisticsDetail2.setLogtsStatus(VenOrderLogisticsEnum.STOCK_UP.getValue());
					orderLogisticsDetail2.setLogtsDesc(XeVenOrderMsg.getLogtsNodeMsg(VenOrderLogisticsEnum.STOCK_UP.getValue(),null));
					this.xeVenOrderLogisticsService.insertLogisticsDetail(orderLogisticsDetail2);
				}*/
            } else {
                this.xeVenOrderLogisticsService.updateLogisticsDetailLogtsCode(orderLogisticsDetail);
            }
        }
        return flag;
    }

    /**
     * 取消审核修改物流信息
     */
    private void deleteOrderLogistics(XeVenOrderLogistics orderLogistics, String storeName) {
        XeVenOrderLogisticsForm orderLogisticsForm = new XeVenOrderLogisticsForm();
        orderLogisticsForm.setUserCode(orderLogistics.getUserCode());
        orderLogisticsForm.setOrderId(orderLogistics.getOrderId());
        List<XeVenOrderLogisticsDetail> orderLogisticsList = this.xeVenOrderLogisticsService.selectLogisticsDetailList(orderLogisticsForm);
        orderLogistics.setLogtsCode(orderLogisticsList.get(XeConstans._XE_ZERO).getLogtsCode());
        xeVenOrderLogisticsService.updateLogisticsByLogtsCode(orderLogistics);

        XeVenOrderLogisticsDetail orderLogisticsDetail = new XeVenOrderLogisticsDetail();
        orderLogisticsDetail.setLogtsCode(orderLogistics.getLogtsCode());
        orderLogisticsDetail.setDelFlag(VenDelEnum.YES.getValue());
        orderLogisticsDetail.setLogtsStatus(XeConstans._XE_TWO);
        xeVenOrderLogisticsService.updateLogisticsDetailLogtsCode(orderLogisticsDetail);

		/*orderLogisticsDetail.setCreateUser(orderLogistics.getCreateUser());
		orderLogisticsDetail.setUserCode(orderLogistics.getUserCode());
		orderLogisticsDetail.setLogtsCode(orderLogistics.getLogtsCode());
		orderLogisticsDetail.setLogtsStatus(orderLogistics.getLogtsStatus());
		orderLogisticsDetail.setDelFlag(VenDelEnum.NO.getValue());
		orderLogisticsDetail.setLogtsDesc(XeVenOrderMsg.getLogtsNodeMsg(VenOrderLogisticsEnum.STORE_IN.getValue(),storeName,null,null));
		xeVenOrderLogisticsService.insertLogisticsDetail(orderLogisticsDetail);*/
    }

    /**
     * 订单配送方式为配送、委托自提的订单，确认实发前需先进行派车操作，即该类订单，确认实发时，校验该订单是否派车：
     * （1）若未派车，提示“您的订单尚未派车，请先进行派车操作，如有疑问，请联系”
     *
     * @param orderId 订单号
     * @return true 订单可以进行后续流程
     * false 订单不可以进行后续流程
     * @author zhouys
     */
    private boolean checkShipType(String orderId) {
        Map<String, Object> param = new HashMap<>(2);
        param.put("orderId", orderId);
        XeVenOrderInfoEntity orderInfoEntity1 = xeVenOrderReadMapper.getOrderInfo(param);
        Integer shipType = orderInfoEntity1.getShipType();
        //判断是否为配送、委托自提的订单
        if (VenShipTypeEnum.DISTRIBUTION.getValue().equals(shipType) || VenShipTypeEnum.ENTRUST.getValue().equals(shipType)) {
            XeVenOrderLogisticsView xeVenOrderLogisticsView = xeVenOrderLogisticsReadMapper.queryOrderLogisticsByOrderId(orderId);
            if (xeVenOrderLogisticsView.getCarSendStatus().equals(XeConstans._XE_ONE)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 单条订单实发数量
     *
     * @author ruancz
     * @since 2017年7月25日 下午20:31:10
     */
    @Override
    @Transactional(value = "writeTransactionManager")
    public Map<String, Object> updateOrderSendNum(ErpUserInfo userInfo, XeVenSplitOrderForm xeVenSplitOrderForm, String requestIP, SysCmsPagePlatEnum platEnum) throws Exception {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put(XeVenBusConstans.CODE, XeVenBusConstans.BUSSINESS_SUCCESS);
        resultMap.put(XeVenBusConstans.MSG, XeVenOrderMsg.SUCCESS);
        //判断订单对应仓库是否零采和分拨仓库
        XeVenStoreInfoEntity storeInfo = this.xeVenStoreInfoReadMapper.getStoreInfoByMap(xeVenSplitOrderForm.getStoreId(), userInfo.getUserCode());
        if (VenStoreTypeEnum.ALLOCATE_STORE.getValue().equals(storeInfo.getStoreType()) || VenStoreTypeEnum.ZERO_STORE.getValue().equals(storeInfo.getStoreType())) {
            // 调接口判断对应采购单是否财审审核通过
            XeVenPurchForm xeVenPurchForm = new XeVenPurchForm();
            xeVenPurchForm.setOrderId(xeVenSplitOrderForm.getOrderId());
            xeVenPurchForm.setUserCode(userInfo.getUserCode());
            List<XeVenPurchView> purchViewList = xeVenPurchService.queryPurchList(xeVenPurchForm);
            log.info("采购单状态查询数据为 {}", JSON.toJSONString(purchViewList));
            //审核通过
            if (null == purchViewList || purchViewList.size() < 1) {
                resultMap.put(XeVenBusConstans.CODE, XeVenBusConstans.BUSSINESS_ERROR);
                resultMap.put(XeVenBusConstans.MSG, XeVenOrderMsg.SUMMARY_PURCH_ERROR);
                return resultMap;
            } else if (!purchViewList.get(0).getCheckStatus().equals(VenPurchCheckEnum.CHECKED.getValue())) {
                log.info("订单号: {},财务审核不通过不可以修改实发,采购单号为: {}", xeVenSplitOrderForm.getOrderId(), purchViewList.get(0).getPurchOrder());
                //审核不通过  则不能修改实发
                resultMap.put(XeVenBusConstans.CODE, XeVenBusConstans.BUSSINESS_ERROR);
                resultMap.put(XeVenBusConstans.MSG, XeVenOrderMsg.REAL_SEND_NUM_ERROR);
                return resultMap;
            }
        }
        Map<String, Object> param = new HashMap<>(2);
        String orderId = xeVenSplitOrderForm.getOrderId();
        //判断是否为配送、委托自提的订单
        if (!checkShipType(orderId)) {
            resultMap.put(XeVenBusConstans.CODE, XeVenBusConstans.BUSSINESS_ERROR);
            resultMap.put(XeVenBusConstans.MSG, XeVenOrderMsg.REAL_SEND_NOT_SEND_CAR_ERROR);
            return resultMap;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("orderId", xeVenSplitOrderForm.getOrderId());
        map.put("userCode", userInfo.getUserCode());
        XeVenOrderInfoEntity confirm = this.xeVenOrderWriteMapper.queryOrderInfo(map);
        if (VenOrderStatusEnum.CANCEL.getValue().equals(confirm.getOrderStatus())) {
            resultMap.put(XeVenBusConstans.CODE, XeVenBusConstans.BUSSINESS_ERROR);
            resultMap.put(XeVenBusConstans.MSG, "该订单已取消,请操作其他订单");
            return resultMap;
        }
        //仓库接入TMS  判断是否已经发货
        if (VenStoreTmsStatusEnum.YES.getValue().equals(storeInfo.getTmsStatus()) && VenOrderConfirmEnum.YES.getValue().equals(confirm.getConfirmSendNum())) {
            boolean flag = this.supplyChainService.judgeSendGood(storeInfo.getStoreId(), xeVenSplitOrderForm.getOrderId());
            if (flag) {
                log.info("订单号: {}已做物流发货，无法再次修改实发量。", xeVenSplitOrderForm.getOrderId());
                resultMap.put(XeVenBusConstans.CODE, XeVenBusConstans.BUSSINESS_ERROR);
                resultMap.put(XeVenBusConstans.MSG, XeVenOrderMsg.REAL_SEND_NUM_FAIL);
                return resultMap;
            }
            //取消供应链信息
            boolean result = this.supplyChainService.cancelOrder(xeVenSplitOrderForm.getOrderId(), xeVenSplitOrderForm.getStoreId());
            if (result) {
                log.info("订单号: {}供应链取消失败，无法再次修改实发量。", xeVenSplitOrderForm.getOrderId());
                resultMap.put(XeVenBusConstans.CODE, XeVenBusConstans.BUSSINESS_ERROR);
                resultMap.put(XeVenBusConstans.MSG, "系统正在处理中,请稍后重试!");
                return resultMap;
            }
        }
        //判断是否实发为零
        StringBuffer operContent = new StringBuffer(platEnum.getName());
        operContent.append("修改订单【" + xeVenSplitOrderForm.getOrderId() + "】内");
        int result = 0;
        for (int i = 0; i < xeVenSplitOrderForm.getSplitOrderDetailList().size(); i++) {
            XeVenSplitOrderDetailForm detailForm = xeVenSplitOrderForm.getSplitOrderDetailList().get(i);
            operContent.append("商品【" + detailForm.getProSku() + "】实发量为" + detailForm.getRealSendNum() + "。");
            if (detailForm.getRealSendNum().compareTo(BigDecimal.ZERO) == 0) {
                result += 1;
            }
        }
        //实发为零订单置为取消状态
        if (result == xeVenSplitOrderForm.getSplitOrderDetailList().size()) {
            log.info("订单号 : {}实发为零订单取消", xeVenSplitOrderForm.getOrderId());
            XeVenOrderInfoEntity orderInfoEntity = new XeVenOrderInfoEntity();
            orderInfoEntity.setOrderId(xeVenSplitOrderForm.getOrderId());
            orderInfoEntity.setUserCode(userInfo.getUserCode());
            orderInfoEntity.setStoreId(xeVenSplitOrderForm.getStoreId());
            orderInfoEntity.setModfiyUser(userInfo.getLoginName());
            orderInfoEntity.setOrderStatus(VenOrderStatusEnum.CANCEL.getValue());
            orderInfoEntity.setPayType(xeVenSplitOrderForm.getPayType());
            orderInfoEntity.setEpayReceAmt(new BigDecimal("0"));
            orderInfoEntity.setCancelRemark("商品库存不足,实发为零,订单取消。");
            orderInfoEntity.setOldOrderStatus(VenOrderStatusEnum.WAIT_SEND.getValue());
            int flag = this.xeVenOrderWriteMapper.updateXeVenOrderInfo(orderInfoEntity);
            orderInfoEntity.setCancelRemark("商品库存不足。");
            XeVenOrderInfoDetailEntity venOrderInfoDetailEntity = new XeVenOrderInfoDetailEntity();
            venOrderInfoDetailEntity.setOrderId(orderInfoEntity.getOrderId());
            venOrderInfoDetailEntity.setRealSendNum(new BigDecimal("0"));
            venOrderInfoDetailEntity.setUserCode(userInfo.getUserCode());
            this.xeVenOrderWriteMapper.updateXeVenOrderInfoDetailByOrderId(venOrderInfoDetailEntity);
            if (XeConstans._XE_ZERO == flag) {
                resultMap.put(XeVenBusConstans.CODE, XeVenBusConstans.BUSSINESS_ERROR);
                resultMap.put(XeVenBusConstans.MSG, XeVenOrderMsg.ERROR);
                return resultMap;
            }
            if (VenOrderPayTypeEnum.ARRIVE_PAY.getValue() == orderInfoEntity.getPayType()) {
                orderInfoEntity.setPayStatus(VenOrderPayStatusEnum.UNPAID.getValue());
            } else {
                orderInfoEntity.setPayStatus(VenOrderPayStatusEnum.ALL_PAID.getValue());
            }
            //删除退款单
            if (VenOrderConfirmEnum.YES.getValue() == confirm.getConfirmSendNum()) {
                //已确认货到付款更新易支付金额
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("orderId", orderInfoEntity.getOrderId());
                params.put("userCode", userInfo.getUserCode());
                if (VenOrderPayTypeEnum.ARRIVE_PAY.getValue() == orderInfoEntity.getPayType()) {
                    List<XeVenOrderInfoEntity> xeVenOrderInfoEntities = this.xeVenOrderReadMapper.queryOrderInfoByParams(params);
                    this.xeVenEpayService.updatePostOrder(orderInfoEntity.getOrderId(), XeConstans._XE_STR_ZERO, xeVenOrderInfoEntities.get(0).getEpayAccount());
                }
                if (orderInfoEntity.getPayType() == VenOrderPayTypeEnum.ONLINE_PAY.getValue()) {
                    params.put("modifyUser", userInfo.getLoginName());
                    this.xeVenOrderRefundWriteMapper.delRefundByOrderId(params);
                }
            }
            //释放库存
            judeCancelOrder(orderInfoEntity, userInfo);
            //零采分拨  取消采购单
            if (VenStoreTypeEnum.ALLOCATE_STORE.getValue() == storeInfo.getStoreType() || VenStoreTypeEnum.ZERO_STORE.getValue() == storeInfo.getStoreType()) {
                Map<String, Object> params = new HashMap<>();
                unBatchOrder(orderInfoEntity, storeInfo, params);
            }
            //供应链取消订单
			/*orderInfoEntity.setStoreName(storeInfo.getStoreName());
			if (VenStoreTmsStatusEnum.YES.getValue() == storeInfo.getTmsStatus() && VenOrderConfirmEnum.YES.getValue() == xeVenSplitOrderForm.getConfirmSendNum()) {
				//取消供应链信息
				this.supplyChainService.cancelOrder(orderInfoEntity.getOrderId(),xeVenSplitOrderForm.getStoreId());
			}*/
            log.info("订单号: {}实发为零, 取消订单。", xeVenSplitOrderForm.getOrderId());
            resultMap.put(XeVenBusConstans.MSG, XeVenOrderMsg.CANCEL_ORDER_MSG);

            return resultMap;
        }
        //查询订单和订单明细信息  计算实发差异金额
        XeVenOrderInfoEntity orderInfo = new XeVenOrderInfoEntity();
        List<XeVenOrderInfoDetailEntity> orderInfoDetailList = new ArrayList<XeVenOrderInfoDetailEntity>();

        orderInfo.setOrderId(xeVenSplitOrderForm.getOrderId());
        orderInfo.setModfiyUser(userInfo.getLoginName());
        orderInfo.setConfirmSendNum(VenConfirmSendNumEnum.YES.getValue());
        orderInfo.setStoreId(xeVenSplitOrderForm.getStoreId());
        orderInfo.setUserCode(userInfo.getUserCode());
        orderInfo.setPayType(xeVenSplitOrderForm.getPayType());
        //订单差异总金额
        BigDecimal orderDifferenceAmount = new BigDecimal("0");

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("orderId", orderInfo.getOrderId());
        params.put("userCode", userInfo.getUserCode());
        //查询订单以及信息  推送订单使用
        XeVenOrderInfoEntity orderInfoEntity = this.xeVenOrderReadMapper.getOrderInfo(params);
        //如果收货店铺名称为空  去发货仓库
        if (StringUtils.isBlank(orderInfoEntity.getStoreName())) {
            orderInfoEntity.setStoreName(storeInfo.getStoreName());
        }
        //退款明细集合
        List<Map<String, Object>> orderRefundList = new ArrayList<Map<String, Object>>();
        //退款单id
        String refundCode = FinanceSeqUtil.seqUtils.createRefundCode();

        for (int i = 0; i < xeVenSplitOrderForm.getSplitOrderDetailList().size(); i++) {
            XeVenSplitOrderDetailForm orderDetailForm = xeVenSplitOrderForm.getSplitOrderDetailList().get(i);
            params.put("proSku", orderDetailForm.getProSku());
            params.put("itemId", orderDetailForm.getItemId());
            List<XeVenOrderInfoDetailEntity> orderDetailList = this.xeVenOrderReadMapper.getOrderDetailByParam(params);
            orderDetailList.get(XeConstans._XE_ZERO).setDifferenceAmount(new BigDecimal("0"));
            orderDetailList.get(XeConstans._XE_ZERO).setRealSendNum(orderDetailForm.getRealSendNum() == null ? new BigDecimal("0") : orderDetailForm.getRealSendNum());
            //计算订单明细差异金额
            XeVenOrderInfoDetailEntity orderInfoDetail = CalUtils.getProDifferenceAmount(orderDetailList.get(XeConstans._XE_ZERO));
            orderInfoDetail.setOrderId(orderInfo.getOrderId());
            orderInfoDetail.setUserCode(userInfo.getUserCode());
            orderInfoDetail.setModifyUser(userInfo.getLoginName());
            orderInfoDetail.setDifferenceAmount(orderInfoDetail.getDifferenceAmount() == null ? new BigDecimal("0") : orderInfoDetail.getDifferenceAmount());
            orderDifferenceAmount = orderDifferenceAmount.add(orderInfoDetail.getDifferenceAmount());
            //退款明细信息
            if (orderInfoDetail.getDifferenceAmount().compareTo(BigDecimal.ZERO) != 0) {
                Map<String, Object> orderRefundMap = new HashMap<String, Object>();
                orderRefundMap.put("refundCode", refundCode);
                orderRefundMap.put("proSku", orderInfoDetail.getProSku());
                orderRefundMap.put("itemId", orderInfoDetail.getItemId());
                orderRefundMap.put("buyNums", orderInfoDetail.getPurchaseNum());
                orderRefundMap.put("refundAmount", orderInfoDetail.getDifferenceAmount());
                orderRefundMap.put("rejectNums", orderInfoDetail.getPurchaseNum().subtract(orderInfoDetail.getRealSendNum()));
                log.info("新建退款明细 :{}", orderRefundMap);
                orderRefundList.add(orderRefundMap);
            }
            orderInfoDetailList.add(orderInfoDetail);
        }
        //运费差异金额
        BigDecimal differenceFreRefundAmount = CalUtils.getProDifferenceRefundAmount(orderDifferenceAmount, orderInfoEntity);
        //订单实发金额
        BigDecimal payAmount = CalUtils.getPayAmount(orderInfoEntity, orderDifferenceAmount);
        orderInfo.setDifferenceAmount(orderDifferenceAmount.add(differenceFreRefundAmount));
        orderInfo.setEpayReceAmt(payAmount);
        //更新订单
        int flag = this.xeVenOrderWriteMapper.updateXeVenOrderInfo(orderInfo);
        if (flag != XeConstans._XE_ONE) {
            log.info("订单号:{} 修改实发更新订单失败", orderInfo.getOrderId());
            resultMap.put(XeVenBusConstans.MSG, XeVenOrderMsg.ERROR);
            return resultMap;
        }
        this.xeVenOrderWriteMapper.updateBatchOrderInfoDetail(orderInfoDetailList);

        // 先查是否有退款  然后再删除更新退款记录
        Integer countRefund = this.xeVenOrderRefundReadMapper.queryCountByOrderId(params);
        log.info("查询订单退款单结果 :{}", countRefund);
        if (VenOrderPayTypeEnum.ARRIVE_PAY.getValue() != orderInfo.getPayType()) {
            if (null != orderRefundList && orderRefundList.size() > XeConstans._XE_ZERO) {
                if (countRefund == XeConstans._XE_ZERO) {
                    //插入退款单信息
                    insertRefound(userInfo, orderInfo, orderDifferenceAmount, orderRefundList, refundCode, differenceFreRefundAmount);
                } else {
                    params.put("modifyUser", userInfo.getLoginName());
                    int delFlag = this.xeVenOrderRefundWriteMapper.delRefundByOrderId(params);
                    log.info("订单号:{}删除原退款单信息结果: {}", orderInfo.getOrderId(), delFlag == XeConstans._XE_ZERO ? "失败" : "成功");
                    //插入退款单信息
                    insertRefound(userInfo, orderInfo, orderDifferenceAmount, orderRefundList, refundCode, differenceFreRefundAmount);
                }
            } else {
                if (!countRefund.equals(XeConstans._XE_ZERO)) {
                    params.put("modifyUser", userInfo.getLoginName());
                    int delFlag = this.xeVenOrderRefundWriteMapper.delRefundByOrderId(params);
                    log.info("订单号:{}删除原退款单信息结果: {}", orderInfo.getOrderId(), delFlag == XeConstans._XE_ZERO ? "失败" : "成功");
                }
            }
        }
        //仓库接入TMS
        if (VenStoreTmsStatusEnum.YES.getValue().equals(storeInfo.getTmsStatus())) {
            //已确认实发 则取消供应链信息 重新推送实发数量
            if (VenConfirmSendNumEnum.YES.getValue().equals(confirm.getConfirmSendNum())) {
                //重新推送实发数量
                this.supplyChainService.insertSupplyChainOrder(orderInfoEntity, orderRefundList, requestIP, userInfo);
                //修改易支付付款订单
                if (orderInfoEntity.getPayType().equals(VenOrderPayTypeEnum.ARRIVE_PAY.getValue())) {
                    this.xeVenEpayService.updatePostOrder(orderInfo.getOrderId(), payAmount.toString(), orderInfoEntity.getEpayAccount());
                }
            } else {
                //易支付接口创建相应金额的支付单
                if (orderInfoEntity.getPayType().equals(VenOrderPayTypeEnum.ARRIVE_PAY.getValue())) {
                    this.xeVenEpayService.insertPostOrder(orderInfo.getOrderId(), payAmount.toString(), orderInfoEntity.getEpayAccount());
                }
                //将实发推送供应链
                this.supplyChainService.insertSupplyChainOrder(orderInfoEntity, orderRefundList, requestIP, userInfo);
            }
        } else { //未接入TMS
            if (VenConfirmSendNumEnum.YES.getValue().equals(confirm.getConfirmSendNum())) {
                //修改易支付付款订单
                if (orderInfoEntity.getPayType().equals(VenOrderPayTypeEnum.ARRIVE_PAY.getValue())) {
                    this.xeVenEpayService.updatePostOrder(orderInfo.getOrderId(), payAmount.toString(), orderInfoEntity.getEpayAccount());
                }
            } else {
                //易支付接口创建相应金额的支付单
                if (orderInfoEntity.getPayType().equals(VenOrderPayTypeEnum.ARRIVE_PAY.getValue())) {
                    this.xeVenEpayService.insertPostOrder(orderInfo.getOrderId(), payAmount.toString(), orderInfoEntity.getEpayAccount());
                }
            }
        }
        insertMqLog(ErpLogTypeEnum.erpOrderModifyRealSendNum.getValue(), orderInfo.getOrderId(), operContent.toString(), userInfo, requestIP, null);
        if (xeVenSplitOrderForm.getConfirmSendNum().equals(VenOrderConfirmEnum.NO.getValue())) {
            //物流信息
            XeVenOrderLogistics orderLogistics = new XeVenOrderLogistics();
            orderLogistics.setUserCode(userInfo.getUserCode());
            orderLogistics.setOrderId(orderInfo.getOrderId());
            orderLogistics.setLogtsStatus(VenOrderLogisticsEnum.WAIT_SEND.getValue());
            updateOrderLogistics(orderLogistics, null);
        }

        return resultMap;
    }

    /**
     * 在线支付插入退款单明细信息
     */
    private void insertRefound(ErpUserInfo userInfo, XeVenOrderInfoEntity orderInfo, BigDecimal orderDifferenceAmount, List<Map<String, Object>> orderRefundList, String refundCode, BigDecimal differenceFreRefundAmount) throws Exception {
        log.info("新建退款单开始 ::{}", orderInfo.getOrderId());
        //新建退款单
        XeVenOrderRefundEntity orderRefund = new XeVenOrderRefundEntity();
        orderRefund.setRefundCode(refundCode);
        orderRefund.setUserCode(userInfo.getUserCode());
        orderRefund.setRefundSource(VenOrderRefundSourceEnum.AUTO.getValue());
        orderRefund.setRealRefundedAmount(orderDifferenceAmount);
        orderRefund.setFreAmount(differenceFreRefundAmount);
        orderRefund.setOrderId(orderInfo.getOrderId());
        orderRefund.setRefundType(VenOrderRefundTypeEnum.DIFFERENCE.getValue());
        orderRefund.setRefundReason(VenOrderRefundReasonEnum.WEIGHT_DIFFERENCE.getValue());
        orderRefund.setRefundStatus(VenOrderRefundStatusEnum.PENDING.getValue()); //退款单 待确认退款状态
        orderRefund.setAutomaticFlag(XeConstans._XE_ONE);
        orderRefund.setCreateUser(userInfo.getLoginName());
        orderRefund.setCreateDate(new Date());
        int result = this.xeVenOrderRefundWriteMapper.insert(orderRefund);
        if (result == XeConstans._XE_ZERO) {
            log.info("订单号:{} 修改订单插入退款单失败");
            throw new RuntimeException("插入退款单失败,修改实发异常");
        }
        this.xeVenOrderRefundDetailWriteMapper.insertAllOrderRefundDetail(orderRefundList);
    }

    /**
     * 订单汇总采购取消审核
     *
     * @author ruancz
     * @since 2017年8月5日 下午14:30:19
     */
    @Override
    @Transactional(value = "writeTransactionManager")
    public Map<String, Object> cancelAuditSummaryPurch(ErpUserInfo userInfo, List<XeVenOrderForm> xeVenOrderForm, String requestIP) throws Exception {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put(XeVenBusConstans.CODE, XeVenBusConstans.BUSSINESS_SUCCESS);
        int result = 0;
        int size = xeVenOrderForm.size();
        for (int i = 0; i < size; i++) {
            XeVenOrderForm orderForm = xeVenOrderForm.get(i);
            if (null == orderForm || StringUtils.isBlank(orderForm.getOrderId())) {
                continue;
            }
            XeVenOrderInfoEntity orderinfo = new XeVenOrderInfoEntity();
            orderinfo.setOrderId(orderForm.getOrderId());
            orderinfo.setOrderStatus(VenOrderStatusEnum.WAIT_CHECK.getValue());
            orderinfo.setVersion(orderForm.getVersion());
            int flag = this.xeVenOrderWriteMapper.updateXeVenOrderInfo(orderinfo);
            result += flag;

            //添加物流信息
            XeVenOrderLogistics orderLogistics = new XeVenOrderLogistics();
            orderLogistics.setUserCode(userInfo.getUserCode());
            orderLogistics.setOrderId(orderinfo.getOrderId());
            orderLogistics.setLogtsStatus(VenOrderLogisticsEnum.STORE_IN.getValue());
            orderLogistics.setCreateUser(userInfo.getLoginName());
            deleteOrderLogistics(orderLogistics, orderForm.getStoreName());
            insertMqLog(ErpLogTypeEnum.erpOrderModifySumPurchUnCheck.getValue(), orderinfo.getOrderId(), "取消订单【" + orderinfo.getOrderId() + "】的审核。", userInfo, requestIP, null);
        }
        if (result == size) {
            resultMap.put(XeVenBusConstans.MSG, XeVenOrderMsg.ORDER_CANCEL_MSG);
        } else {
            resultMap.put(XeVenBusConstans.MSG, "订单取消审核成功" + result + "条，失败" + (xeVenOrderForm.size() - result) + "条。");
        }
        return resultMap;
    }

    /**
     * 查询汇总商品
     *
     * @author ruancz
     * @since 2017年8月5日 下午16:31:19
     */
    @Override
    @Transactional(value = "writeTransactionManager")
    public Map<String, Object> countSummaryPurch(ErpUserInfo userInfo, List<XeVenOrderForm> xeVenOrderForm) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("userCoce", userInfo.getUserCode());
        resultMap.put("list", xeVenOrderForm);
        List<XeVenSummaryPurchView> actionList = this.xeVenOrderReadMapper.countSummaryPurch(resultMap);
        resultMap.remove("userCoce");
        resultMap.remove("list");
        resultMap.put("actionList", actionList);
        return resultMap;
    }

    /**
     * 插入汇总采购单
     *
     * @author ruancz
     * @since 2017年8月7日 下午10:30:19
     */
    @Override
    @Transactional(value = "writeTransactionManager")
    public Map<String, Object> insertSummaryPurch(ErpUserInfo userInfo, XeVenOrderFromVo orderFromVo, String requestIP) throws Exception {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put(XeVenBusConstans.CODE, XeVenBusConstans.BUSSINESS_SUCCESS);
        resultMap.put(XeVenBusConstans.MSG, XeVenOrderMsg.SUMMARYPURCH_SUCCESS);

        XeVenPurchOrderEntity purchOrder = new XeVenPurchOrderEntity();
        purchOrder.setStoreId(orderFromVo.getXeVenSplitOrderForm().get(XeConstans._XE_ZERO).getStoreId());
        this.insertPurchOrder(purchOrder, userInfo);
        //插入采购单
        purchOrder.setPurchType(VenPurchTypeEnum.ALLOT_BUY.getValue());
        purchOrder.setAddType(1);
        int result = this.xeVenPurchOrderWriteMapper.insertPurch(purchOrder);

        List<XeVenOrderDetailView> orderInfoDetailList = JSON.parseArray(JSON.toJSONString(orderFromVo.getSplitOrderDetailList()), XeVenOrderDetailView.class);
        log.info("采购单: {},插入采购单结果: {}", JSON.toJSONString(purchOrder), result == XeConstans._XE_ONE ? "成功" : "失败");
        StringBuffer operContent = new StringBuffer();
        operContent.append("对订单");

        if (result == XeConstans._XE_ONE) {
            //新建采购单明细
            List<XeVenPurchOrderDetailEntity> purchOrderDetailList = getPurchOrderDetailList(orderInfoDetailList, purchOrder);
            this.xeVenPurchOrderDetailWriteMapper.insertPurchProductBatch(purchOrderDetailList);
            List<XeVenSplitOrderForm> XeVenSplitOrderForm = orderFromVo.getXeVenSplitOrderForm();

            List<XeVenSummaryPurchEntity> summaryPurchList = new ArrayList<XeVenSummaryPurchEntity>();
            int size = XeVenSplitOrderForm.size();
            for (int i = 0; i < size; i++) {
                XeVenSplitOrderForm orderForm = XeVenSplitOrderForm.get(i);
                XeVenSummaryPurchEntity summaryPurch = new XeVenSummaryPurchEntity();
                summaryPurch.setOrderId(orderForm.getOrderId());
                summaryPurch.setOrderStatus(orderForm.getOrderStatus());
                summaryPurch.setDelFLag(VenDelEnum.NO.getValue());
                summaryPurch.setPurchOrder(purchOrder.getPurchOrder());
                summaryPurch.setAddType(2);
                summaryPurchList.add(summaryPurch);
                operContent.append("【" + orderForm.getOrderId() + "】,");
            }
            //批量插入汇总采购关联关系
            this.xeVenSummaryPurchService.insertBatchXeVenSummaryPurch(summaryPurchList);
            log.info("插入采购单: {}", JSON.toJSONString(summaryPurchList));
            operContent.append("进行汇总采购，生成对应汇总采购单【" + purchOrder.getPurchOrder() + "】。");
            insertMqLog(ErpLogTypeEnum.erpOrderModifySumPurch.getValue(), null, operContent.toString(), userInfo, requestIP, null);
        } else {
            resultMap.put(XeVenBusConstans.MSG, XeVenOrderMsg.SUMMARYPURCH_SUCCESS);
            resultMap.put(XeVenBusConstans.CODE, XeVenBusConstans.BUSSINESS_ERROR);
        }
        log.info("结束零采和分拨仓库订单自动创建采购单,采购单号: {}", purchOrder.getPurchOrder());
        return resultMap;
    }

    @Override
    public List<Map<String, Object>> querySalesMan() {
        return this.xeVenOrderReadMapper.querySalesMan();
    }

    @Override
    public Map<String, Object> queryShopYesterdayData(Map<String, Object> map) {
        return xeVenOrderReadMapper.queryShopYesterdayData(map);
    }

    @Override
    public BigDecimal queryWaitCheckOrderNum(Map<String, Object> map) {
        return xeVenOrderReadMapper.queryWaitCheckOrderNum(map);
    }

    @Override
    public BigDecimal queryExceptionOrderNum(Map<String, Object> map) {
        return xeVenOrderReadMapper.queryExceptionOrderNum(map);
    }

    @Override
    public BigDecimal queryWaitSendOrderNum(Map<String, Object> map) {
        return xeVenOrderReadMapper.queryWaitSendOrderNum(map);
    }

    @Override
    public BigDecimal queryMonthTotalAmount(Map<String, Object> map) {
        return xeVenOrderReadMapper.queryMonthTotalAmount(map);
    }

    @Override
    public BigDecimal queryMonthTradeUserNum(Map<String, Object> map) {
        return xeVenOrderReadMapper.queryMonthTradeUserNum(map);
    }

    /**
     * 添加日志
     */
    @Override
    public void insertMqLog(String logType, String key, String operatorContent, ErpUserInfo userInfo, String ipAddress, String remark) {
        try {
            if (StringUtils.isBlank(logType)) {
                logType = ErpLogTypeEnum.erpOrder.getValue();
            }
            if (StringUtils.isNotBlank(remark)) {
                OpertorLogUtil.opertorLog.sendOperatorLogByParam(ipAddress, key, logType, userInfo.getLoginName(), operatorContent, userInfo.getUserCode(), remark);
            } else {
                OpertorLogUtil.opertorLog.sendOperatorLogByParam(ipAddress, key, logType, userInfo.getLoginName(), operatorContent, userInfo.getUserCode());
            }
        } catch (Exception e) {
            log.error("订单中心MQ日志插入失败,logType={},operatorContent={}", logType, operatorContent);
        }
    }

    /**
     * 订单手动关联采购单
     */
    @Override
    @Transactional(value = "writeTransactionManager")
    public Map<String, Object> insertOrderRelationPurch(List<XeVenOrderRelationPurchForm> orderRelationPurchForm) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        List<XeVenSummaryPurchEntity> list = JSON.parseArray(JSON.toJSONString(orderRelationPurchForm), XeVenSummaryPurchEntity.class);
        list.stream().forEach(sumpur -> sumpur.setAddType(VenOrderSumPurAddTypeEnum.MANUAL.getValue()));
//		Map<String, List<XeVenSummaryPurchEntity>> groupByOrderId = list.stream().collect(groupingBy(sumPur -> sumPur.getOrderId()));
//		Map<String,Object> params = new HashMap<String, Object>();
        int count = 0;
	/*	//此时是一个订单对应多个采购单 判断是否关联
		if (groupByOrderId.size() == 1) {
			params.put("orderId",list.get(0).getOrderId());
			params.put("purchList",list);
			count = this.xeVenSummaryPurchService.queryExistsSumPurchByParams(params);
		} else {
			//多个订单对应一个采购单
//			params.put("purchOrder",list.get(0).getOrderId());  rcz
			params.put("purchOrder",list.get(0).getPurchOrder());
			params.put("orderList",list);
			count = this.xeVenSummaryPurchService.queryExistsSumPurchByParams(params);
		}
		if (count == 0) {
			count = this.xeVenSummaryPurchService.insertBatchXeVenSummaryPurch(list);
			if (count == list.size()) {
				resultMap.put(XeVenBusConstans.CODE, XeVenBusConstans.BUSSINESS_SUCCESS);
				resultMap.put(XeVenBusConstans.MSG,XeVenOrderMsg.ORDER_SUCCESS);
			}
		} else {
			resultMap.put(XeVenBusConstans.CODE, XeVenBusConstans.BUSSINESS_ERROR);
			resultMap.put(XeVenBusConstans.MSG,XeVenOrderMsg.ORDER_STATUS_CHANGE);
		}*/

        count = this.xeVenSummaryPurchService.insertBatchXeVenSummaryPurch(list);
        if (count == list.size()) {
            resultMap.put(XeVenBusConstans.CODE, XeVenBusConstans.BUSSINESS_SUCCESS);
            resultMap.put(XeVenBusConstans.MSG, XeVenOrderMsg.ORDER_SUCCESS);
        } else {
            resultMap.put(XeVenBusConstans.CODE, XeVenBusConstans.BUSSINESS_ERROR);
            resultMap.put(XeVenBusConstans.MSG, XeVenOrderMsg.ORDER_STATUS_CHANGE);
        }
        return resultMap;
    }

    /**
     * 根据订单ID查询订单信息
     *
     * @author RCZ
     */
    @Override
    public List<XeVenOrderInfoEntity> queryOrderStatusByOrderId(String orderId) {
        return xeVenOrderReadMapper.queryOrderStatusByOrderId(orderId);
    }

    /**
     * 鲜易消消乐取消订单
     *
     * @author RCZ
     */
    @Override
    @Transactional(value = "writeTransactionManager")
    public int cancelOrderByorderId(XeVenOrderInfoEntity orderInfoEntity, String requestIP) {
        OrderInfoDTO orderInfoDTO = new OrderInfoDTO();
        orderInfoDTO.setMorderId(orderInfoEntity.getMainOrderId());
        orderInfoDTO.setUserId(orderInfoEntity.getUserId());
        orderInfoDTO.setCancelUser(orderInfoEntity.getCancelUser());
        try {
            log.info("鲜易消消乐取消订单推送商城入参: {}", JSON.toJSONString(orderInfoDTO));
            OrderInfoResDTO orderInfoResDTO = orderInfoApiService.offOrder(orderInfoDTO);
            log.info("鲜易消消乐取消订单推送商城出参: {}", JSON.toJSONString(orderInfoResDTO));
            if ("2000".equals(orderInfoResDTO.getStatus())) {
                return 1;
            }
        } catch (Exception e) {
            log.error("鲜易消消乐取消订单推送商城：{}", e);
        }
		/*if ("2000".equals(orderInfoResDTO.getStatus())) {
			orderInfoEntity.setOrderId(null);
			orderInfoEntity.setOldOrderStatus(VenOrderStatusEnum.WAIT_DIS.getValue());
			orderInfoEntity.setOrderStatus(VenOrderStatusEnum.CANCEL.getValue());
			int result = this.xeVenOrderWriteMapper.updateOrderInfo(orderInfoEntity);
			return result;
		} else {
			return 0;
		}*/
        return 0;
    }

    /**
     * 查询写库订单明细信息
     *
     * @author 李贝贝
     * @since 2018年5月16日 下午2:07:22
     */
    @Override
    public List<XeVenOrderInfoDetailEntity> getWriteOrderDetailByParam(Map<String, Object> params) {
        return xeVenOrderWriteMapper.getOrderDetailByParam(params);
    }

    /**
     * 某个产品（spu）在订单记录中被多少条订单占用
     * 订单状态包括 待分配、待审核、待发货 均表示为spu被占用
     *
     * @param spu 产品spu
     * @return 多少个订单中包含此订单
     * @author zhouys
     */
    @Override
    public int spuTakeUpCount(String spu) {
        return xeVenOrderReadMapper.spuTakeUpCount(spu);
    }
}